问题
Is there a way to include html partial inside another partial using webpack? I am using html-loader to do this:
index.html
<%= require('html-loader!./partials/_header.html') %>
But when I try to include another partial inside a _header.html it is not able to render it.
This is not working:
_header.html
<%= require('html-loader!./partials/_nav.html') %>
回答1:
I was combining a little and I was able to find a solution.
index.html
<%= require('html-loader?root=.&minimize=true&interpolate!./partials/_header.html') %>
and then in _header.html
${require('html-loader?root=.!../partials/_nav.html')}
回答2:
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>
html-variables.js
looks like this:
const hello = 'Hello!';
const bye = 'Bye!';
export {hello, bye}
You can also include partials inside another partial the same way, using ${require('path/to/your/partial.html')
.
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), just write the title in your html or use a separate javascript file for handle variables if needed.
来源:https://stackoverflow.com/questions/49168671/webpack-include-html-partial-inside-another-partial