我对webpack和pug如何协同工作有了基本的了解,使用HtmlWebpackPlugin通过pug模板生成带有捆绑资源的页面。
我已经用两个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')
})
]
};发布于 2021-01-10 21:38:33
使用这些加载器对pug文件使用Webpack规则:
...
{
test: /\.pug$/,
use: [
{
loader: 'html-loader'
},
{
loader: 'pug-html-loader'
}
],
},
...也许你可以去掉插件模板属性的!!pug-loader!:
...
new HtmlWebpackPlugin({
template: './src/pug/index.pug',
filename: path.join(__dirname, 'dist/index.html')
})
...您可能需要通过npm安装加载器:
npm i html-loader pug-html-loaderhttps://stackoverflow.com/questions/65627085
复制相似问题