问题描述
我将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'),path.dirname(filePath))
})
在 webpack 中:module.rules
:
{
test: /\.html$/,loader: 'html-loader',options: {
preprocessor: processNestedHtml
}
}
然后你可以把这个 <include>
指令放在你的 html 部分中:
<include src="relative/path/to/partial">
这个 github issue 解决了这个问题:https://github.com/webpack-contrib/html-loader/issues/291