React create-react-app 构建问题?

问题如下: 想要在React 项目执行yarn build 时, 给index.html 增加后缀
没有使用react-eject, 使用的是crao 替代, 但是craco.config.js 配置 HtmlWebpackPlugin不生效。
craco.config.js 配置如下:

const CracoLessPlugin = require('craco-less')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  plugins: [
    {
      plugin: CracoLessPlugin,
    },
  ],
  webpack: {
    plugins: {
      add: [
        [
          new HtmlWebpackPlugin({
            filename: 'index.[contenthash].html',
          }),
          'prepend',
        ],
      ],
    },
  },
}

package.json 部分组件版本如下:

 "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "typescript": "^4.7.2",
    "web-vitals": "^2.1.4"
  }, 
"devDependencies": {
    "@craco/craco": "^7.1.0",
    "craco-less": "^2.0.0",
    "html-webpack-plugin": "^5.5.1",
  }
 "scripts": {
    "dev": "set PORT=4488 && craco start",
    "build": "craco build",
  },

执行yarn build 打包后,配置无效, 请教各位大佬们了

阅读 1.3k
1 个回答

你要直接修改 webpack 配置:

const CracoLessPlugin = require('craco-less');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  plugins: [
    {
      plugin: CracoLessPlugin,
    },
  ],
  webpack: {
    configure: (webpackConfig, { env, paths }) => {
    
      const htmlWebpackPlugin = webpackConfig.plugins.find(
        (plugin) => plugin.constructor.name === 'HtmlWebpackPlugin'
      );

      if (htmlWebpackPlugin) {
        // 修改 HtmlWebpackPlugin 配置
        htmlWebpackPlugin.options.filename = 'index.[contenthash].html';
      }

      return webpackConfig;
    },
  },
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏