如何修改webpackDevServer配置控制script src路径(CRA React项目)
修改CRA项目开发环境下Script标签路径的方法
如果你已经通过 npm run eject 暴露了webpack配置,可以按以下步骤修改:
1. 调整webpack开发环境输出配置
打开项目根目录下的 config/webpack.config.js,找到 output 配置块:
output: { path: undefined, filename: 'static/js/bundle.js', chunkFilename: 'static/js/[name].chunk.js', publicPath: publicPath, // 其他配置... }
将 filename 和 chunkFilename 中的 static/js/ 前缀移除,修改为:
filename: '[name].js', chunkFilename: '[name].chunk.js',
2. 修改webpackDevServer的publicPath配置
打开 config/webpackDevServer.config.js,找到 publicPath 项,将原有的 '/static/' 改为 '/':
publicPath: '/',
完成以上修改后,重启 npm run start,页面DOM中的script标签src就会变成 localhost:3000/xxx.js 的形式。
如果不想执行eject操作,也可以用react-app-rewired来覆盖配置:
- 安装依赖:
npm install react-app-rewired --save-dev
- 在项目根目录创建
config-overrides.js文件,写入以下内容:
module.exports = function override(config, env) { // 修改输出文件路径和publicPath config.output.filename = '[name].js'; config.output.chunkFilename = '[name].chunk.js'; config.output.publicPath = '/'; // 针对开发环境调整devServer配置 if (env === 'development') { config.devServer.publicPath = '/'; } return config; };
- 修改
package.json中的scripts命令:
"scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test", "eject": "react-scripts eject" }
最后重启服务即可生效。
内容的提问来源于stack exchange,提问作者user6389584
相关产品推荐
相关产品推荐

