html-webpack-injector在同一个html文档中不同的位置如head、body处注入脚本,依赖HtmlWebpackPlugin的chunks属性。
npm i --save-dev html-webpack-injector
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackInjector = require('html-webpack-injector');
module.exports = {
entry: {
index: "./index.ts",
index_head: "./index.ts" // add "_head" at the end to inject in head.
},
output: {
path: "./dist",
filename: "[name].bundle.js"
},
plugins: [
new HtmlWebpackPlugin({
template: "./index.html",
filename: "./dist/index.html",
chunks: ["index", "index_head"]
}),
new HtmlWebpackInjector() // Initialize plugin
]
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Archit's App</title>
<script type="text/javascript" src="index_head.bundle.js"></script></head>
</head>
<body>
<script src="index_bundle.js"></script>
</body>
</html>
您必须在entry入口属性名称以_head命名,这样它将自动注入头部。