webpack - 如何在 webpack 中包含加载器?

标签 webpack header include

我正在尝试包含 Header.html还有footer.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>

但它显示在页面enter image description here

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

那么该怎么做呢?

最佳答案

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 文件将被注入(inject)到您指定的带有页眉和页脚文件内容的位置。

关于webpack - 如何在 webpack 中包含加载器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50098523/

相关文章:

javascript - 如何在 babel-loader 和 flow 中使用 webpack

reactjs - 我应该通过 .babelrc 还是 WebPack 配置 Babel?

c++ - C4430 和 C2146 Visual Studio 错误

c++ - 内存标准头和包含文件之间的区别

c - #include 在嵌入的头文件中

visual-studio - 在 typescript 中导入模块时绝对路径的根是什么?

javascript - 使用 Webpack 从 SASS 导入 CSS-url

c++ - 无法使用在不同头文件中定义的结构

http - 如何在 nginx 中添加规范 header 和 301 重定向

JavaScript 包括