webpack html-loader预处理器中有什么方法可以插入HTML文件吗?

问题描述

我将Webpack与html-loader一起使用,但是由于它们删除了interpolation选项,所以我的旧项目无法遵循更新。有服务器项目,因此将所有项目升级到新方法将花费太多精力。

是否可以通过preprocessor选项使用此语法?

<header>
  ${require('./components/header/header.html')}
</header>

解决方法

您可以使用 preprocessorhtml-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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...