问题
I am using Webpack to compile my scripts and HTML (using html-webpack-plugin). The thing is, I have 5 HTML files that contains the same parts and I want to move these parts to separate .html files and then include these parts in every HTML file. This way, if I will change these smaller HTML files, it will recompile every HTML file to represent these changes.
Webpack does this for .js files by default, but can I use something like that for HTML files?
回答1:
You can use <%= require('html!./partial.html') %> in your template. Example here: https://github.com/jantimon/html-webpack-plugin/blob/master/examples/custom-template/template.html
回答2:
Another slightly different solution.
Using html-loader with interpolate option.
https://github.com/webpack-contrib/html-loader#interpolation
{ test: /\.(html)$/,
include: path.join(__dirname, 'src/views'),
use: {
loader: 'html-loader',
options: {
interpolate: true
}
}
}
And then in html pages you can import partials html and javascript variables.
<!-- Importing top <head> section -->
${require('./partials/top.html')}
<title>Home</title>
</head>
<body>
<!-- Importing navbar -->
${require('./partials/nav.html')}
<!-- Importing variable from javascript file -->
<h1>${require('../js/html-variables.js').hello}</h1>
<!-- Importing footer -->
${require('./partials/footer.html')}
</body>
html-variables.js looks like this:
const hello = 'Hello!';
const bye = 'Bye!';
export {hello, bye}
The only downside is that you can't import other variables from HtmlWebpackPlugin like this <%= htmlWebpackPlugin.options.title %> (at least I can't find a way to import them) but for me it's not an issue, just write the title in your html or use a separate javascript file for handle variables.
回答3:
Check out Partials for HTML Webpack Plugin for something a little more elegant. It lets you set up HTML files and include them similar to what you're looking for simply like:
plugins: [
new HtmlWebpackPlugin(),
new HtmlWebpackPartialsPlugin({
path: './path/to/partials/body.html'
})
]
Also configurable for where it gets added such as head vs body, opening vs closing, and lets you pass in variables.
来源:https://stackoverflow.com/questions/42193689/is-there-a-way-to-include-partial-using-html-webpack-plugin