React前端如何正确调用Webpack生成的带chunkhash的动态打包文件?
解决Webpack动态chunkhash文件名的引入问题
当你把Webpack输出文件名改成带[chunkhash]的动态命名后,手动写死的<script>路径自然会失效,下面是几种靠谱的解决方式:
方法一:使用HtmlWebpackPlugin(推荐)
这是Webpack官方推荐的方案,插件会自动扫描打包后的文件,把带chunkhash的正确路径注入到HTML中,完全不用手动维护。
- 安装依赖
npm install html-webpack-plugin --save-dev
- 修改webpack.config.js配置
const HtmlWebpackPlugin = require('html-webpack-plugin'); const path = require('path'); module.exports = { // ...其他原有配置 output: { path: path.resolve(__dirname, "../dist/"), publicPath: "auto", filename: "[name].[chunkhash].js", }, plugins: [ new HtmlWebpackPlugin({ template: './public/index.html', // 你的源HTML模板路径 filename: 'index.html', // 输出到dist目录的HTML文件名 inject: 'body' // 自动把脚本注入到body末尾位置 }) ] };
- 清理手动写的script标签
把原来HTML里的<script src="../dist/bundle.js"></script>删掉,插件会自动生成类似<script src="main.xxxxxx.js"></script>的正确标签。
方法二:生成资源清单手动加载(特殊场景用)
如果不想用插件,可以让Webpack生成一个包含所有打包文件路径的JSON清单,再通过JS动态加载脚本。
- 安装assets-webpack-plugin
npm install assets-webpack-plugin --save-dev
- 配置webpack.config.js
const AssetsPlugin = require('assets-webpack-plugin'); const path = require('path'); module.exports = { // ...其他原有配置 plugins: [ new AssetsPlugin({ filename: 'asset-manifest.json', path: path.resolve(__dirname, '../dist/') }) ] };
- 在HTML中动态加载脚本
删除原有的script标签,替换成这段JS:
<script> fetch('../dist/asset-manifest.json') .then(res => res.json()) .then(manifest => { const script = document.createElement('script'); script.src = `../dist/${manifest.main.js}`; document.body.appendChild(script); }); </script>
方法三:区分环境配置(开发调试用)
如果只是开发阶段不想用动态hash(方便调试),可以根据环境变量切换文件名规则:
const isProduction = process.env.NODE_ENV === 'production'; const path = require('path'); module.exports = { output: { path: path.resolve(__dirname, "../dist/"), publicPath: "auto", filename: isProduction ? "[name].[chunkhash].js" : "[name].js", } };
打包生产环境时用npm run build(需在package.json中配置NODE_ENV=production),开发时用npm start,保持固定文件名方便调试。
内容的提问来源于stack exchange,提问作者Ali Raza
相关产品推荐
相关产品推荐

