I'm trying to figure out a way where you can have an index file that when piled loads the global header and footer into the index.html file so I don't have to add this every time.
At the moment this is what creates my index.html file:
new HtmlWebpackPlugin({
title: 'Typescript Webpack Starter',
template: '!!ejs-loader!src/index.html'
}),
It loads the JS in the body and the css in the head fine but I'm wondering if I can do something like the below (just like a template engine would)
<body>
{{HEADER GETS IMPORTED HERE}}
<p>Success your page has loaded</p>
<button class="button">Button</button>
{{FOOTER GETS IMPORTED HERE}}
</body>
Let me know your thoughts
I'm trying to figure out a way where you can have an index file that when piled loads the global header and footer into the index.html file so I don't have to add this every time.
At the moment this is what creates my index.html file:
new HtmlWebpackPlugin({
title: 'Typescript Webpack Starter',
template: '!!ejs-loader!src/index.html'
}),
It loads the JS in the body and the css in the head fine but I'm wondering if I can do something like the below (just like a template engine would)
<body>
{{HEADER GETS IMPORTED HERE}}
<p>Success your page has loaded</p>
<button class="button">Button</button>
{{FOOTER GETS IMPORTED HERE}}
</body>
Let me know your thoughts
Share Improve this question asked Jan 20, 2017 at 12:31 Max LynnMax Lynn 3972 gold badges6 silver badges17 bronze badges3 Answers
Reset to default 1As per the official document : YOU CAN ACHIEVE it.
If you already have a template loader, you can use it to parse the template. Please note that this will also happen if you specifiy the html-loader and use .html file as template.
module: {
loaders: [
{ test: /\.hbs$/, loader: "handlebars" }
]
},
plugins: [
new HtmlWebpackPlugin({
title: 'Custom template using Handlebars',
template: 'my-index.hbs'
})
]
Just in case anybody needs a working example. I did it with an ejs-loader
<div id="page-wrapper">
<%- include partials/header.ejs %>
<div class="content"></div>
<%- include partials/footer.ejs %>
</div>
Also put evth. into a small webpack boilerplate there are some more extras inside ;) feel free to use it.
Since html-loader replaced option interpolate with preprocessor, the solution for webpack5 and html-loader 3.0.1 is:
preprocessor: (content, loaderContext) =>
content.replace(
/<include src="(.+)"\s*\/?>(?:<\/include>)?/gi,
(m, src) => {
const filePath = path.resolve(loaderContext.context, src)
loaderContext.dependency(filePath)
return fs.readFileSync(filePath, 'utf8')
}
),
Solution I've got from here github after a half of hours of surfing. Probably it helps to someone.