1

我将 Webpack 与 html-loader 一起使用,但由于他们删除了该interpolation选项,我的旧项目无法遵循更新。有多个项目,因此将它们全部升级到新方式将花费太多精力。

有没有办法将此语法与preprocessor选项一起使用?

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

1 回答 1

0

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

于 2021-04-16T15:02:04.197 回答