【问题标题】:how to include loaders in webpack?如何在 webpack 中包含加载器?
【发布时间】:2018-10-10 10:21:15
【问题描述】:

我正在尝试将Header.htmlfooter.html 包含在index.html 中。因为我将使用这两个文件作为所有页面的通用文件。由于我的研究 webpack 不允许将文件导入为

<!--#include file="header.html"-->

我已经尝试过 grunt 我工作正常。但是如何在 webpack 中做

这是我的 webpack 版本详情

"name": "webpack-boilerplate",
"version": "1.0.0",

这是我尝试过的... 在我的 webpack.config.js 文件中

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

在我的 index.html 文件中

<body>
    require("html-loader!./file.html");
    <div class="banner">
        <h3>Banner 1</h3>
    </div>
    <div class="banner banner2">
        <h3>Banner 2</h3>
    </div>
</body>

但它显示在页面

这不是为了反应。这仅适用于网站和普通 html..

那该怎么做呢?

【问题讨论】:

  • 你是在使用 html-webpack-plugin 来加载 index.html 文件吗?
  • 是的@lukas-reineke

标签: webpack header include


【解决方案1】:

html-webpack-plugin 支持使用变量进行模板化。

您可以在webpack.config.js 中定义变量

new HtmlWebpackPlugin({
    template: './src/index.html',
    header: '<h1>hello world</h1>',
    fotter: '<b>Footer</b>'
}),

然后像这样将它们放在你的 index.html 中:

<html>
    <head></head>
    <body>
        <%= htmlWebpackPlugin.options.header %>
        <!-- all your standard template here -->
        <%= htmlWebpackPlugin.options.footer %>
    </body>
</html>

要从普通 HTML 文件加载页眉和页脚需要额外的步骤,我们为此使用内置的 fs 节点包(您不必安装它)。

let fs = require('fs');

const header = fs.readFileSync(__dirname + '/header.html');
const footer = fs.readFileSync(__dirname + '/footer.html');

module.exports = {

    // all of your normal config

    plugins: [
      new HtmlWebpackPlugin({
        template: './src/index.html',
        header: header,
        footer: footer,
      })
     ]
});

现在,当您运行 webpack 时,您的 HTML 文件将被注入到您指定的带有页眉和页脚文件内容的位置。

【讨论】:

  • 是的,当然@lukas
  • 这里提到的所有正常配置是什么意思?我很困惑
  • @RND 你在 webpack 配置中的所有其他东西,比如 entry output module
  • 是的,但它不起作用..我正在搜索如何在 index.html 中导入 header.html
  • 如果您愿意,可以编辑您的吗?你让我找到了解决方案,
猜你喜欢
  • 2016-04-09
  • 2016-10-15
  • 2017-07-16
  • 1970-01-01
  • 1970-01-01
  • 2018-07-11
  • 2017-02-08
  • 2016-03-29
  • 1970-01-01
相关资源
最近更新 更多