如何为React构建后index.html的资源路径添加{{DOMAIN}}前缀?
在React应用build后给资源路径添加{{DOMAIN}}前缀
当使用react-scripts build构建后,index.html中的资源引用都是以/开头的绝对路径,要给这些路径统一添加{{DOMAIN}}前缀,有以下几种可行方案:
方案1:Post-build脚本处理(无需eject)
这种方式不需要修改webpack配置,在build完成后直接修改生成的index.html文件,适合快速实现。
跨平台Node.js脚本
- 在项目根目录创建
postbuild.js文件:
const fs = require('fs'); const path = require('path'); const indexHtmlPath = path.join(__dirname, 'build', 'index.html'); let htmlContent = fs.readFileSync(indexHtmlPath, 'utf8'); // 匹配所有src/href属性中以/开头的路径,替换为{{DOMAIN}}/开头 htmlContent = htmlContent.replace(/(src|href)="\//g, '$1="{{DOMAIN}}/'); fs.writeFileSync(indexHtmlPath, htmlContent);
- 修改
package.json中的scripts,添加postbuild命令:
"scripts": { "build": "react-scripts build", "postbuild": "node postbuild.js" }
Shell脚本(适用于Linux/macOS)
如果你的开发环境是Linux或macOS,可以直接用sed命令:
"scripts": { "build": "react-scripts build", "postbuild": "sed -i '' 's/src=\"\\//src=\"{{DOMAIN}}\\//g' build/index.html && sed -i '' 's/href=\"\\//href=\"{{DOMAIN}}\\//g' build/index.html" }
注意:Linux环境下sed无需
-i '',直接用-i即可。
方案2:修改Webpack配置(通过react-app-rewired)
如果需要在build过程中直接生成带前缀的路径,可以用react-app-rewired和customize-cra来修改webpack配置,无需eject。
- 安装依赖:
npm install customize-cra react-app-rewired --save-dev
- 在项目根目录创建
config-overrides.js:
const { override, adjustHtmlPlugin, adjustWorkbox } = require('customize-cra'); module.exports = override( // 修改html-webpack-plugin的publicPath,给资源路径加前缀 adjustHtmlPlugin(htmlPlugin => { htmlPlugin.options.publicPath = '{{DOMAIN}}/'; return htmlPlugin; }), // 如果项目使用了Workbox(默认create-react-app会用),同步修改其publicPath adjustWorkbox(workboxConfig => { workboxConfig.config.publicPath = '{{DOMAIN}}/'; return workboxConfig; }) );
- 修改
package.json中的scripts:
"scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test", "eject": "react-scripts eject" }
方案3:Eject后修改Webpack配置
如果你已经执行了npm run eject,可以直接修改生成的webpack.config.js:
找到HtmlWebpackPlugin的配置项,将publicPath设置为'{{DOMAIN}}/':
new HtmlWebpackPlugin( Object.assign( {}, { inject: true, template: paths.appHtml, publicPath: '{{DOMAIN}}/' // 添加这一行 }, isEnvProduction ? { minify: { removeComments: true, collapseWhitespace: true, removeRedundantAttributes: true, useShortDoctype: true, removeEmptyAttributes: true, removeStyleLinkTypeAttributes: true, keepClosingSlash: true, minifyJS: true, minifyCSS: true, minifyURLs: true, }, } : undefined ) ),
同时,找到workbox-webpack-plugin的配置,同步修改publicPath参数。
内容的提问来源于stack exchange,提问作者Ergis
相关产品推荐
相关产品推荐

