1

I use the Webpack with html-loader, but since they removed the interpolation option my old projects can't follow the updates. There are serveral projects, so it would be too much effort to upgrade all of them to the new way.

Is there any way to use this syntax with the preprocessor option?

<header>
  ${require('./components/header/header.html')}
</header>
Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
netdjw
  • 5,419
  • 21
  • 88
  • 162

1 Answers1

0

You can use the preprocessor property of the html-loader to achieve interpolation:preprocessor

I use it like this:

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))
  })

And in webpack: module.rules:

      {
        test: /\.html$/, loader: 'html-loader', options: {
          preprocessor: processNestedHtml
        }
      }

Then you can put this <include> directive in your html partials:

<include src="relative/path/to/partial">

This github issue addresses the problem: https://github.com/webpack-contrib/html-loader/issues/291

stWrong
  • 334
  • 2
  • 14