自定义webpack配置中HtmlWebpackPlugin引入静态JS文件不生效咨询
问题原因
原生HtmlWebpackPlugin并没有提供scripts配置项,你在配置中自定义的该参数无法被插件原生逻辑识别,因此不会自动生成对应的script标签插入到编译后的HTML中。同时public目录下的静态资源默认不会被webpack处理到产物目录,需要额外配置资源拷贝。
解决方案
方案1:通过模板变量插入(无需额外安装HTML相关插件)
- 调整HtmlWebpackPlugin配置,修正scripts路径为产物访问路径:
new HtmlWebpackPlugin({ inject: true, filename: './index.html', template: './public/index.html', favicon: './public/favicon.ico', // 自定义参数会传入模板上下文 scripts: ['./static/js/env.js'] }),
- 修改
public/index.html模板,在需要插入静态脚本的位置(如body末尾)添加模板语法遍历输出script标签:
<body> <div id="app"></div> <!-- 插入自定义静态脚本 --> <% for (const src of htmlWebpackPlugin.options.scripts) { %> <script src="<%= src %>"></script> <% } %> </body>
- 安装
copy-webpack-plugin拷贝public下的静态资源到产物目录:
- 安装依赖:
npm install copy-webpack-plugin --save-dev - 新增插件配置:
const CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { // 其他配置... plugins: [ // 原有其他插件... new CopyWebpackPlugin({ patterns: [ { from: './public/static', to: 'static' } ] }) ] }
方案2:使用扩展插件自动插入(无需修改HTML模板)
可以使用html-webpack-tags-plugin配合HtmlWebpackPlugin自动插入静态资源标签:
- 安装依赖:
npm install copy-webpack-plugin html-webpack-tags-plugin --save-dev - 调整webpack插件配置:
const HtmlWebpackPlugin = require('html-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const HtmlWebpackTagsPlugin = require('html-webpack-tags-plugin'); module.exports = { // 其他配置... plugins: [ new HtmlWebpackPlugin({ inject: true, filename: './index.html', template: './public/index.html', favicon: './public/favicon.ico' }), // 自动插入静态脚本标签 new HtmlWebpackTagsPlugin({ tags: ['./static/js/env.js'], append: false // 配置为true则插在webpack打包生成的脚本之后,false则插在前面 }), // 拷贝静态资源,配置同方案1 new CopyWebpackPlugin({ patterns: [ { from: './public/static', to: 'static' } ] }) ] }
补充说明
如果你的env.js需要被webpack编译处理,可以直接将其添加到webpack的entry入口配置中,webpack会自动将其打包并插入到HTML中,无需额外配置拷贝和标签插入。
内容的提问来源于stack exchange,提问作者RyanP13
相关产品推荐
相关产品推荐

