How to use webpack to concat html pieces?
You can use this plugin github.com/bazilio91/ejs-compiled-loader:
{ test: /\.ejs$/, use: 'ejs-compiled-loader' }
Change your .html
files in .ejs
and your HtmlWebpackPlugin
to point to the right .ejs
template:
new HtmlWebpackPlugin({
template: 'src/views/index.ejs',
filename: 'index.html',
title: 'Home',
chunks: ['index']
})
You can import partials, variables, and assets in .ejs
files:
src/views/partials/head.ejs
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
src/js/ejs_variables.js
:
const hello = 'Hello!';
const bye = 'Bye!';
export {hello, bye}
src/views/index.ejs
:
<% include src/views/partials/head.ejs %>
<body>
<h2><%= require("../js/ejs_variables.js").hello %></h2>
<img src=<%= require("../../assets/sample_image.jpg") %> />
<h2><%= require("../js/ejs_variables.js").bye %></h2>
</body>
A note, when you include a partial the path must be relative to the root of your project.
I answered the same question here stackoverflow.com/a/48750048/7448956.
There is a couple of loaders to achieve this: https://webpack.github.io/docs/list-of-loaders.html#templating
For example:
html-loader
<div>${require('./partials/gallery.html')}</div>
ejs-html-loader
<% include some/file %>