I am trying to generate a more ore less static html page using HtmlWebpackPlugin and Handlebars. Where everything works like a charm, using templateContent (function) instead of template (path) as an option of HtmlWebpackPlugin, img src is not updated in html when building.
Here is index.html (at: 'src/templates/index.html'):
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>{{ hello_world }}</h1>
<img src="~assets/images/image.svg">
</body>
</html>
(I also tried "../../assets/images/image.svg" which has same results)
Here is output index.html (at: 'dist/index.html'):
<!DOCTYPE html>
<html>
<head>
<link rel="shortcut icon" href="http://localhost/favicon.png"><link href="http://localhost/main.e0aba7a5294a4bfca93a1b95f4dc194a.css" rel="stylesheet"></head>
<body>
<h1>Hello World</h1>
<img src="~assets/images/image.svg">
<script type="text/javascript" src="http://localhost/main.js"></script></body>
</html>
I am expecting the output index.html to have img src path updated like so:
<img src="http://localhost/img/image.svg">
Here is my (simplified) webpack.config.js:
const path = require('path');
const fs = require('fs');
const Handlebars = require('handlebars');
const HtmlWebpackPlugin = require('html-webpack-plugin');
...
module.exports = {
entry: ['./assets/styles/main.scss', './src/scripts/main.js'],
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
publicPath: 'http://localhost/',
},
resolve: {
alias: {
'assets': path.resolve(__dirname, 'assets'),
},
},
module: {
rules: [
...
{
test: /\.html$/,
use: ['html-loader'],
},
{
test: /\.(jpg|png|svg)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'img/',
}
}
]
},
...
]
},
plugins: [
...
new HtmlWebpackPlugin({
filename: 'index.html',
favicon: 'assets/images/favicon.png',
templateContent: function(templateParams) {
const templatePath = path.resolve(__dirname, 'src/templates/index.html');
var source = fs.readFileSync(templatePath, 'utf8');
const context = require('./assets/data.json');
return Handlebars.compile(source)(context);
},
})
]
};
My package.json rughly looks like so:
{
...
"devDependencies": {
...
"file-loader": "0.11.2",
"handlebars": "4.0.10",
"html-loader": "0.5.1",
"html-webpack-plugin": "2.30.1",
"url-loader": "0.5.9",
"webpack": "3.5.5",
},
...
}
For now, I am replacing img src by hand in templateContent which kind of feels hacky.
(Note: Another issue I encountered is that hot reloading with webpack-dev-server won't work with this config. To fix this, I am actually also using template option in HtmlWebpackPlugin. Described problem remains same.)
Hope anyone has some ideas to get it working properly. Thanks!