我正在尝试替换index.html中的一个变量,如下所示:
<meta name='author' content=$variable>
在我使用的配置文件中:
{
test: /index\.html$/,
loader: 'string-replace',
query: {
search: '$variable',
replace: 'stuff to inject',
},
}在loaders数组中,然后在plugins中
new HtmlWebpackPlugin({
template: conf.path.src('src/index.html'),
inject: true,
})但此设置会导致:
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.
你知道这是什么原因造成的吗?或者我怎么调试它?
发布于 2016-08-14 03:42:26
这是因为string-replace-plugin需要一个导出字符串的模块。你应该把HTML文件转换成CommonJS模块。
例如,这就是使用raw-loader的方法
首先,在html的content属性中添加引号。
<meta name='author' content='$variable'>`和
{
test: /index\.html$/,
loader: 'string-replace?search=$variable&replace=stuff to inject!raw'
}发布于 2016-10-28 18:47:25
康斯坦丁的答案很好用,如果你想替换一个值,这是很好的。我想替换多个值,因此将以下内容添加到loaders数组中
{
test: /\.html$/,
loader: 'raw'
},
{
test: /\.html$/,
loader: 'string-replace',
query: {
multiple: [
{search: '$variable1', replace: 'replacement 1'},
{search: '$variable2', replace: 'replacement 2'}
]
}
}关键的更改是首先通过raw加载器运行html文件,然后可以使用string-replace-loader的所有常规配置。
发布于 2021-02-27 20:07:13
对@Jonathon Blok的答案进行了更新,但对于Webpack 4,做了一些细微的修改:
npm install --save-dev string-replace-loader@2.'raw-loader'和'string-replace-loader'标识符,因为webpack@4坚持要使用。string-replace-loader文档使用了options:而不是query:。<代码>H213<代码>F214献给Webpack 4
{
test: /.*\.html$/,
loader: 'raw-loader',
},
{
test: /.*\.html$/,
loader: 'string-replace-loader',
options: {
multiple: [
{search: '$variable1', replace: 'replacement 1'},
{search: '$variable2', replace: 'replacement 2'} ]
}
}和以前一样,
替换关键的更改是首先通过原始加载器运行html文件,然后您可以使用字符串替换加载器的所有常规配置。
献给Webpack 5
通过省略@2并使用npm install --save-dev string-replace-loader安装字符串加载器,应该可以在Webpack 5上使用上面的方法,尽管我还没有对其进行测试。这是因为根据string-replace-loader docs,字符串替换加载器的v3应该与Webpack 5+一起工作。
https://stackoverflow.com/questions/38359842
复制相似问题