首页 > 解决方案 > Webpack 4 的变化

问题描述

我目前正在使用 reactcreateapp 的 webpack 4.32,我想重命名输出文件的格式。当前它使用波浪号(~)作为文件名中的分隔符,例如命中 runtime~main.167ad0b7.js.map。我想用破折号代替波浪号。我该如何改变呢?

我试着用谷歌搜索它,它说我需要调整

自动名称分隔符:'~'

但不幸的是,我认为在 Webpack 4 中它们会改变你配置事物的方式。当我搜索它时可以看到这一点,但我尝试在破折号中对其进行硬编码,但它不起作用,并且属性旁边的问号是什么?TIA

 interface SplitChunksOptions {
        /** Select chunks for determining shared modules (defaults to \"async\", \"initial\" and \"all\" requires adding these chunks to the HTML) */
        chunks?: "initial" | "async" | "all" | ((chunk: compilation.Chunk) => boolean);
        /** Minimal size for the created chunk */
        minSize?: number;
        /** Maximum size for the created chunk */
        maxSize?: number;
        /** Minimum number of times a module has to be duplicated until it's considered for splitting */
        minChunks?: number;
        /** Maximum number of requests which are accepted for on-demand loading */
        maxAsyncRequests?: number;
        /** Maximum number of initial chunks which are accepted for an entry point */
        maxInitialRequests?: number;
        /** Give chunks created a name (chunks with equal name are merged) */
        name?: boolean | string | ((...args: any[]) => any);
        /** Assign modules to a cache group (modules from different cache groups are tried to keep in separate chunks) */
        cacheGroups?: false | string | ((...args: any[]) => any) | RegExp | { [key: string]: CacheGroupsOptions | false };
        /** Override the default name separator (~) when generating names automatically (name: true)  */
        automaticNameDelimiter?: string;
    }

标签: reactjswebpack-4

解决方案


弹出后,config/webpack.config.js

- new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime~.+[.]js/]),
+ new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime-.+[.]js/]),
- runtimeChunk: true
+ runtimeChunk: {
+   name: entrypoint => `runtime-${entrypoint.name}`
+ }

并查看插件的文档split-chunks-plugin

// after ejecting, config/webpack.config.js:246
splitChunks: {
  chunks: 'all',
  name: true, // <--
  automaticNameDelimiter: '---boom---', // <--
},

这会产生类似的东西

build/static/js/vendors---boom---main.b41502e9.chunk.js
build/static/js/vendors---boom---main.b41502e9.chunk.js.map

您还可以output.filename在 webpack 配置中添加一个函数而不是字符串:

// after ejecting, config/webpack.config.js:246
filename: isEnvProduction
  ? ({ chunk, ...rest }) => {
    // just for debug
    console.log(JSON.stringify(({chunk, rest}))); 
    return `static/js/${chunk.name.replace('~', '-')}.[contenthash:8].js` 
  }
  : isEnvDevelopment && 'static/js/bundle.js',

我想你明白了,我添加了一些用于调试的 console.log。


推荐阅读