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?
This means Webpack has successfully bundled both our logic from src/index. js and HTML from src/index. html into the dist directory, even automatically linking them together for us. And this is just the beginning of what Webpack can do!
The HtmlWebpackPlugin simplifies creation of HTML files to serve your webpack bundles. This is especially useful for webpack bundles that include a hash in the filename which changes every compilation.
The html-loader will parse the URLs, require the images and everything you expect. The extract loader will parse the javascript back into a proper html file, ensuring images are required and point to proper path, and the asset modules will write the .html file for you. Example: webpack.config.js module.
Loaders work at the individual file level during or before the bundle is generated. Plugins: Plugins work at bundle or chunk level and usually work at the end of the bundle generation process. Plugins can also modify how the bundles themselves are created.
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'
}
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
.
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