Using Webpack 4 and it's HtmlWebpackPlugin and html-loader together, I'm trying to:
However, this doesn't work when html-loader is present in webpack.config.js.
If I could use the same syntax that would be preferred, but I already tried using ${ }
for the title tag but i get an build error, htmlWebpackPlugin undefined
.
<!doctype html>
<html>
<head>
<title><%= htmlWebpackPlugin.options.title %></title> <!-- this doesn't work -->
<!-- <title>${htmlWebpackPlugin.options.title}</title> //also doesn't work -->
</head>
<body>
<section>${require("./path/to/other.html")}</section> <!-- this works fine -->
</body>
</html>
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
entry: './src/main.js',
devServer: {
contentBase: './src',
port: 4200,
open: true
},
plugins: [
new HtmlWebpackPlugin({
hash: true,
template: './src/index.html'},
title: 'Index Page')
],
module: {
rules: [
{
test: /\.jsx?$/,
include: /src/,
exclude: /node_modules/
},
{
test: /\.(html)$/,
exclude: /node_modules/,
use: {
loader: 'html-loader',
options: {
attrs:[':data-src'],
minimize: false,
conservativeCollapse: false,
interpolate: true
}
}
},
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[path][name]__[local]--[hash:base64:5]'
}
}
]
}
]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
}
It can be achieved by stacking up the following loaders in this sequence:
{
test: /\.html$/,
use: [{
loader: 'ejs-loader'
}, {
loader: 'extract-loader'
}, {
loader: 'html-loader',
options: {
interpolate: true
}
}
html-loader
kicks in first replacing interpolated fragments, then we need to extract resulting HTML - that's why we use extract-loader
and then ejs-loader
can then replace ejs
fragments and it does see htmlWebpackPlugin
variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With