Reputation: 2770
I'm trying to replace a variable in index.html that looks like this:
<meta name='author' content=$variable>
In the config file I use:
{
test: /index\.html$/,
loader: 'string-replace',
query: {
search: '$variable',
replace: 'stuff to inject',
},
}
In the loaders
array, and then in plugins
:
new HtmlWebpackPlugin({
template: conf.path.src('src/index.html'),
inject: true,
})
But this setting results in:
ERROR in ./~/html-webpack-plugin/lib/loader.js!./src/index.html
Module parse failed (...) Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
Do you have any ideas what this can be caused by or how can I debug this?
Upvotes: 10
Views: 9881
Reputation: 124
An update to @Jonathon Blok's answer, but for Webpack 4, with some slight modifications:
npm install --save-dev string-replace-loader@2
.'raw-loader'
and 'string-replace-loader'
identifiers because webpack@4 insisted.options:
instead of query:
as per the string-replace-loader
docs.{
test: /.*\.html$/,
loader: 'raw-loader',
},
{
test: /.*\.html$/,
loader: 'string-replace-loader',
options: {
multiple: [
{search: '$variable1', replace: 'replacement 1'},
{search: '$variable2', replace: 'replacement 2'} ]
}
}
As before,
The key change is to first run your html file through the raw loader, and then you can use all the normal config for the string-replace-loader.
Same as above should work for Webpack 5, though I haven't tested it, by omitting the @2
and installing string-loader with npm install --save-dev string-replace-loader
. This is because v3 of the string-replace-loader is expected to work with Webpack 5+, as per the string-replace-loader docs.
Upvotes: 3
Reputation: 749
Konstantin's answer works fine and is good if you want to replace one value. I wanted to replace multiple values so added the following to my loaders
array
{
test: /\.html$/,
loader: 'raw'
},
{
test: /\.html$/,
loader: 'string-replace',
query: {
multiple: [
{search: '$variable1', replace: 'replacement 1'},
{search: '$variable2', replace: 'replacement 2'}
]
}
}
The key change is to first run your html file through the raw
loader, and then you can use all the normal config for the string-replace-loader
.
Upvotes: 3
Reputation: 61
It's caused because of string-replace-plugin
expects a module that exporting a string. You should convert HTML file to CommonJS module.
For example, this is the way by using raw-loader
:
first, add quotes to content attribute in html
<meta name='author' content='$variable'>`
and
{
test: /index\.html$/,
loader: 'string-replace?search=$variable&replace=stuff to inject!raw'
}
Upvotes: 6