【问题标题】:How to change the CSS bundle name using a Webpack config override in CRA?如何使用 CRA 中的 Webpack 配置覆盖更改 CSS 包名称?
【发布时间】:2021-08-26 12:37:52
【问题描述】:

我目前有一个config-overrides.js 文件,用于更改 Create React App 为 JS 文件生成的包名称。我希望能够将类似的逻辑应用于我的 CSS 包。

以下是配置覆盖文件的内容:

module.exports = function override(config, webpackEnv) {
  const isEnvDevelopment = webpackEnv === 'development';
  const isEnvProduction = webpackEnv === 'production';

  config.output.filename = isEnvProduction
    ? 'static/js/[name].js?nocache=[contenthash:8]'
    : isEnvDevelopment && 'static/js/bundle.js';
  config.output.chunkFilename = isEnvProduction
    ? 'static/js/[name].chunk.js?nocache=[contenthash:8]'
    : isEnvDevelopment && 'static/js/[name].chunk.js';

  return config
}

除了 CSS 包/块,我如何才能获得相同的结果?

编辑:我注意到我跳过了使用react-app-rewired 进行配置覆盖这一事实。

【问题讨论】:

    标签: javascript css webpack bundle create-react-app


    【解决方案1】:

    我不这么认为,尤其是在当前这个时间。 CRA 有一个可以破坏整个过程的技巧。 CRA 落后了,postcss 当前版本是 8,CRA 使用的一些包使用 postcss 版本 7,v8 带有中断更改。即使您能够做到这一点,您也无法在不弹出的情况下修复其余部分。

    但是,有一个巨大的但是,CRA 在他们的插件部分使用这个 webpack。

    of the problems.new MiniCssExtractPlugin({
                // Options similar to the same options in webpackOptions.output
                // both options are optional
                filename: "static/css/[name].[contenthash:8].css",
                chunkFilename: "static/css/[name].[contenthash:8].chunk.css",
            }), 
    

    他们还有一个 webpack 加载器

        // "file" loader makes sure those assets get served by WebpackDevServer.
                        // When you `import` an asset, you get its (virtual) filename.
                        // In production, they would get copied to the `build` folder.
                        // This loader doesn't use a "test" so it will catch all modules
                        // that fall through the other loaders.
                        {
                            loader: require.resolve("file-loader"),
                            // Exclude `js` files to keep "css" loader working as it injects
                            // its runtime that would otherwise be processed through "file" loader.
                            // Also exclude `html` and `json` extensions so they get processed
                            // by webpacks internal loaders.
                            exclude: [ /\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/ ],
                            options: {
                                name: "static/media/[name].[hash:8].[ext]",
                            },
                        },
    

    【讨论】:

    • 按预期工作。我们将在接下来的几周左右迁移到 Next.js,所以这是一个很好的临时解决方案。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 2022-01-22
    • 2014-10-27
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 2017-11-21
    相关资源
    最近更新 更多