我将 Webpack 与 html-loader 一起使用,但由于他们删除了该interpolation
选项,我的旧项目无法遵循更新。有多个项目,因此将它们全部升级到新方式将花费太多精力。
有没有办法将此语法与preprocessor
选项一起使用?
<header>
${require('./components/header/header.html')}
</header>
我将 Webpack 与 html-loader 一起使用,但由于他们删除了该interpolation
选项,我的旧项目无法遵循更新。有多个项目,因此将它们全部升级到新方式将花费太多精力。
有没有办法将此语法与preprocessor
选项一起使用?
<header>
${require('./components/header/header.html')}
</header>
可以使用 的preprocessor
属性html-loader
来实现插值:preprocessor
我这样使用它:
const INCLUDE_PATTERN = /<include src="(.+)"\s*\/?>(?:<\/include>)?/gi
const processNestedHtml = (content, loaderContext, dir = null) =>
!INCLUDE_PATTERN.test(content) ? content : content.replace(INCLUDE_PATTERN, (m, src) => {
const filePath = path.resolve(dir || loaderContext.context, src)
loaderContext.dependency(filePath)
return processNestedHtml(loaderContext.fs.readFileSync(filePath, 'utf8'), loaderContext, path.dirname(filePath))
})
在 webpack module.rules
:中
{
test: /\.html$/, loader: 'html-loader', options: {
preprocessor: processNestedHtml
}
}
然后你可以把这个<include>
指令放在你的 html 部分中:
<include src="relative/path/to/partial">
这个github问题解决了这个问题:https ://github.com/webpack-contrib/html-loader/issues/291