问题
I am absolutely new to Webpack and I work with scss and vue on a little project. What I try is to compile all my .scss files to css and bundle them up in a bundle.css that is automatically injected into the head (I already set up the sass and css loaders to archieve the bundling to css). But I also want my vue app.js bundle at the end of the body, also injected by the htmlWebpackPlugin (already done). Using a single HtmlWebpackPlugin to put everything in my index.html would leave me with either the style in the body or the javascript in the head.
My first guess would be, that I have to define 2 Plugin-Instances like
var jsInjectorPlugin = new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: 'body'
});
var cssInjectorPlugin = new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: 'head'
})
But how do I tell webpack, to use the first plugin for css and the other one for js? Since I have no test
like in loaders, I do not know how to do this
So the point of this question is, can someone explain me how I can achieve that my css-bundle gets injected into the head and my js-bundle gets injected in the body? (code snippets of how to do this in the webpack-config are appreciated)
回答1:
You need HtmlWebpackInjector
- It works with
HtmlWebpackPlugin
and by just adding_head
in the name of chunk, it automaticlly injects the chunk in the head.
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackInjector = require('html-webpack-injector');
module.exports = {
entry: {
index: "./index.ts",
// add "_head" in the bundle name to inject in head.
// use sass and css loaders to compile sass to js bundle.
bundle_head: "./index.scss"
},
output: {
path: "./dist",
filename: "[name].bundle.js"
},
plugins: [
new HtmlWebpackPlugin({
template: "./index.html",
filename: "./dist/index.html",
chunks: ["index", "bundle_head"]
}),
new HtmlWebpackInjector()
]
}
This automatically injects index
chunk to the body and bundle_head
to the head of the html document. Final html looks like:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Archit's App</title>
<script type="text/javascript" src="bundle_head.bundle.js"></script> <--injected in head
</head>
</head>
<body>
<script src="index_bundle.js"></script> <--injected in body
</body>
</html>
来源:https://stackoverflow.com/questions/46202546/how-to-inject-css-bundle-in-head-and-js-bundle-in-body-using-webpack-html-plugin