Webpack: include html partial inside another partial?

☆樱花仙子☆ 提交于 2019-12-07 05:37:17

问题


Is there a way to include html partial inside another partial using webpack? I am using html-loader to do this:

index.html

<%= require('html-loader!./partials/_header.html') %>

But when I try to include another partial inside a _header.html it is not able to render it.

This is not working:

_header.html

<%= require('html-loader!./partials/_nav.html') %>

回答1:


I was combining a little and I was able to find a solution.

index.html

<%= require('html-loader?root=.&minimize=true&interpolate!./partials/_header.html') %>

and then in _header.html

${require('html-loader?root=.!../partials/_nav.html')}



回答2:


Using html-loader with interpolate option.

https://github.com/webpack-contrib/html-loader#interpolation

{ test: /\.(html)$/,
  include: path.join(__dirname, 'src/views'),
  use: {
    loader: 'html-loader',
    options: {
      interpolate: true
    }
  }
}

And then in html pages you can import partials html and javascript variables.

<!-- Importing top <head> section -->
${require('./partials/top.html')}
<title>Home</title>
</head>
<body>
  <!-- Importing navbar -->
  ${require('./partials/nav.html')}
  <!-- Importing variable from javascript file -->
  <h1>${require('../js/html-variables.js').hello}</h1>
  <!-- Importing footer -->
  ${require('./partials/footer.html')}
</body>
</html>

html-variables.js looks like this:

const hello = 'Hello!';
const bye = 'Bye!';

export {hello, bye}

You can also include partials inside another partial the same way, using ${require('path/to/your/partial.html').

The only downside is that you can't import other variables from HtmlWebpackPlugin like this <%= htmlWebpackPlugin.options.title %> (at least I can't find a way to import them), just write the title in your html or use a separate javascript file for handle variables if needed.



来源:https://stackoverflow.com/questions/49168671/webpack-include-html-partial-inside-another-partial

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!