webpack html头部 注入脚本
时间: 2023-09-11 14:10:10 浏览: 53
可以使用 `html-webpack-plugin` 插件来在 HTML 头部注入脚本。具体操作如下:
1. 安装 `html-webpack-plugin` 插件:
```bash
npm install --save-dev html-webpack-plugin
```
2. 在 webpack 配置文件中引入插件,并在 `plugins` 中进行配置:
```javascript
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
// ...其他配置
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html', // 模板文件路径
inject: 'head', // 注入位置,默认是 'body'
scriptLoading: 'blocking', // 脚本加载方式,默认是 'defer'
// 其他配置项
}),
// ...其他插件
],
};
```
3. 在模板 HTML 文件中使用模板语法插入脚本:
```html
<!DOCTYPE html>
<html>
<head>
<title>My App</title>
<!-- 在这里使用模板语法插入脚本 -->
<%= htmlWebpackPlugin.options.headScripts %>
</head>
<body>
<!-- 在这里使用模板语法插入脚本 -->
<%= htmlWebpackPlugin.options.bodyScripts %>
</body>
</html>
```
上面的代码中,`<%= htmlWebpackPlugin.options.headScripts %>` 表示插入在头部的脚本,`<%= htmlWebpackPlugin.options.bodyScripts %>` 表示插入在 body 中的脚本。这两个模板语法都是由 `html-webpack-plugin` 自动生成的,不需要手动编写。