You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React打包构建时如何保留public/index.html中的自定义注释并强制换行?

解决方案

方案1:构建后追加注释(最推荐,无需修改任何项目配置)

该方法直接绕开React构建时的注释删除逻辑,在打包完成后自动把目标注释追加到输出的html文件末尾,自带换行,兼容性100%。

  • 打开项目根目录下的package.json文件,找到scripts字段中的build配置
  • 修改为对应命令:
    • Mac/Linux环境:
    "scripts": {
      "start": "react-scripts start",
      "build": "react-scripts build && echo '\n<!-- this project is open source -->' >> build/index.html",
      "test": "react-scripts test",
      "eject": "react-scripts eject"
    }
    
    • Windows cmd环境:
    "scripts": {
      "start": "react-scripts start",
      "build": "react-scripts build && echo. && echo <!-- this project is open source --> >> build/index.html",
      "test": "react-scripts test",
      "eject": "react-scripts eject"
    }
    

修改完成后重新执行npm run build即可得到符合要求的输出文件。

方案2:修改注释格式(无需修改配置,可直接实现)

React底层使用html-minifier-terser压缩html文件,默认会保留带特殊版权标记的注释,你只需要给原有注释开头加感叹号即可避免被删除:

<!--! this project is open source -->

如果需要确保注释前有换行,直接在该注释前加一个空行即可。

方案3:修改html压缩配置(适合需要自定义更多压缩规则的场景)

如果需要全局调整html压缩规则,可以修改HtmlWebpackPlugin的压缩配置:

未eject的Create React App项目

  1. 安装craco依赖:
npm install @craco/craco --save-dev
  1. 项目根目录新建craco.config.js文件,写入以下配置:
module.exports = {
  webpack: {
    configure: (webpackConfig) => {
      // 查找HtmlWebpackPlugin实例
      const htmlPlugin = webpackConfig.plugins.find(
        plugin => plugin.constructor.name === 'HtmlWebpackPlugin'
      )
      // 调整压缩配置
      htmlPlugin.userOptions.minify = {
        ...htmlPlugin.userOptions.minify,
        // 保留指定注释,避免全量注释被删除
        removeComments: true,
        keepComments: /this project is open source/i,
        // 保留换行
        preserveLineBreaks: true
      }
      return webpackConfig
    }
  }
}
  1. 修改package.json中的scripts命令,将react-scripts替换为craco:
"scripts": {
  "start": "craco start",
  "build": "craco build",
  "test": "craco test"
}

已eject或自定义webpack配置的项目

直接在webpack配置中找到HtmlWebpackPlugin的声明,修改上述minify配置即可。

内容的提问来源于stack exchange,提问作者AriaN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 09:51:03