【问题标题】:HtmlWebpackPlugin doesn't pass pug variables to included pug fileHtmlWebpackPlugin 不会将 pug 变量传递给包含的 pug 文件
【发布时间】:2021-04-14 01:09:01
【问题描述】:

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

我创建了一个非常简单的测试项目,其中包含两个 pug 文件:head.pug 包含 <head> 中的内容,index.pug 是其余部分。我在index.pug 中创建了一些变量,我希望通过使用include head.pughead.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,因此未插入 &lt;base&gt;。怎么了?这是我的 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


【解决方案1】:

对带有这些加载器的 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

【讨论】:

  • 这并没有真正回答为什么 pug-loader 不起作用,但是这个解决方案有效,所以我会接受它。谢谢
猜你喜欢
  • 2018-03-17
  • 2017-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-28
  • 2020-04-16
  • 2021-12-31
相关资源
最近更新 更多