繁体   English   中英

Html Webpack 插件 - 如何将页眉/页脚 html 部分导入正文模板

[英]Html Webpack Plugin - How do you import headers/footer html partials into body template

我试图找出一种方法,您可以在其中拥有一个索引文件,该文件在编译时将全局页眉和页脚加载到 index.html 文件中,这样我就不必每次都添加它。

目前这是创建我的 index.html 文件的原因:

    new HtmlWebpackPlugin({
        title: 'Typescript Webpack Starter',
        template: '!!ejs-loader!src/index.html'
    }),  

它在正文中加载 JS,在头部加载 css,但我想知道我是否可以执行以下操作(就像模板引擎一样)

  <body>
       {{HEADER GETS IMPORTED HERE}}
       <p>Success your page has loaded</p>
       <button class="button">Button</button>
       {{FOOTER GETS IMPORTED HERE}}
  </body>

让我知道你的想法

根据官方文件可以实现它。

如果您已有模板加载器,则可以使用它来解析模板。 请注意,如果您指定html-loader并使用.html文件作为模板,也会发生这种情况。

 module: {
   loaders: [
     { test: /\.hbs$/, loader: "handlebars" }
   ]
 },
 plugins: [
   new HtmlWebpackPlugin({
     title: 'Custom template using Handlebars',
     template: 'my-index.hbs'
   })
 ]

以防任何人需要一个有效的例子。 我用ejs-loader做到了

<div id="page-wrapper">
   <%- include partials/header.ejs %>
   <div class="content"></div>
   <%- include partials/footer.ejs %>
</div>

也把evth。 在一个小的webpack样板中,里面还有一些额外的东西;)随意使用它。

由于 html-loader 用预处理器替换了选项 interpolate,所以 webpack5 和 html-loader 3.0.1 的解决方案是:

preprocessor: (content, loaderContext) =>
      content.replace(
        /<include src="(.+)"\s*\/?>(?:<\/include>)?/gi,
        (m, src) => {
          const filePath = path.resolve(loaderContext.context, src)
          loaderContext.dependency(filePath)
          return fs.readFileSync(filePath, 'utf8')
        }
      ),

半小时的冲浪后,我从这里github得到了解决方案。 可能它对某人有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM