【发布时间】:2021-04-14 01:09:01
【问题描述】:
我对 webpack 和 pug 如何协同工作有了基本的了解,使用 pug 模板使用 HtmlWebpackPlugin 生成包含捆绑资产的页面。
我创建了一个非常简单的测试项目,其中包含两个 pug 文件:head.pug 包含 <head> 中的内容,index.pug 是其余部分。我在index.pug 中创建了一些变量,我希望通过使用include head.pug 在head.pug 中使用这些变量。以下是它们的样子:
// head.pug //
title #{title}
if isProduction
base(href='myurl.com/welcome/')
// index.pug //
- var isProduction = true
- var title = 'Testing'
doctype html
html
head
include head.pug
body
p My Site
如果我使用pug-cli 编译index.pug,它会创建以下index.html 文件:
<!DOCTYPE html>
<html>
<head>
<title>Testing</title>
<base href="myurl.com/welcome/">
</head>
<body>
<p>My Site</p>
</body>
</html>
看起来不错。现在,如果我使用webpack 构建我的资产并生成index.html,它看起来像这样:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>My Site</p>
<script src="/bundle6028aa4f7993fc1329ca.js"></script>
</body>
</html>
如您所见,未定义标题,并且 isProduction 为 false,因此未插入 <base>。怎么了?这是我的 webpack 配置文件:
const webpack = require('webpack');
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/js/index.js',
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle[contenthash].js'
},
module: {
rules: [
{ test: /\.pug$/, loader: "pug-loader" },
]
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: '!!pug-loader!src/pug/index.pug',
filename: path.join(__dirname, 'dist/index.html')
})
]
};
【问题讨论】:
-
应该可以。如何调用或渲染 pug 文件?
-
@kmgt 你是对的,它确实有效。但是,这是直接使用 pug 的。如果我使用 HtmlWebpackPlugin,它就不起作用。我重写了这个问题。
标签: variables webpack pug html-webpack-plugin