HtmlWebpackPlugin 不会将 pug 变量传递给包含的 pug 文件

问题描述

我对 webpackpug 如何协同工作有基本的了解,使用 HtmlWebpackPlugin 使用 pug 模板生成包含捆绑资产的页面

我用两个 pug 文件创建了一个非常简单的测试项目:head.pug 包含 <head> 中的内容,而 index.pug 是其余部分。我在 index.pug 中创建了一些我希望通过使用 head.puginclude 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 文件使用 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-loader