我想包括Header.html也footer.html内index.html。因为我将使用这两个文件作为所有页面的通用文件。由于我的研究Webpack不允许将文件导入为
<!--#include file="header.html"-->
Run Code Online (Sandbox Code Playgroud)
我苦苦尝试,我工作得很好。但是如何在webpack中做
这是我的webpack版本详细信息
"name": "webpack-boilerplate",
"version": "1.0.0",
Run Code Online (Sandbox Code Playgroud)
这是我尝试过的...在我的webpack.config.js文件中
{
test: /\.html$/,
loader: 'html-loader'
}
Run Code Online (Sandbox Code Playgroud)
在我的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>
Run Code Online (Sandbox Code Playgroud)
这不是为了反应。这仅适用于网站和普通html。
那么该怎么做呢?
html-webpack-plugin支持使用变量进行模板化。
您可以在中定义变量 webpack.config.js
new HtmlWebpackPlugin({
template: './src/index.html',
header: '<h1>hello world</h1>',
fotter: '<b>Footer</b>'
}),
Run Code Online (Sandbox Code Playgroud)
然后将它们放在index.html中,如下所示:
<html>
<head></head>
<body>
<%= htmlWebpackPlugin.options.header %>
<!-- all your standard template here -->
<%= htmlWebpackPlugin.options.footer %>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
要从普通的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,
})
]
});
Run Code Online (Sandbox Code Playgroud)
现在,当您运行webpack时,您的HTML文件将被注入到您指定的带有页眉和页脚文件内容的位置。