【问题标题】:Build `html/index.pug` into `dist/index.html` using Webpack 5使用 Webpack 5 将 `html/index.pug` 构建到 `dist/index.html` 中
【发布时间】:2022-01-13 19:46:14
【问题描述】:

我想使用 Webpack 5 将 html/index.pug 构建成 dist/index.html

在 Webpack 4 中,我曾经为此使用 file-loader,但它在 Webpack 5 中似乎已被弃用:Loaders 页面中没有提及它。 Webpack 5 解决方案似乎正在使用 Asset Modules:该页面清楚地表明 file-loader 是 Webpack 4 的旧解决方案。

到目前为止,我还没有让它工作。这些是我在webpack.config.jsmodule.rules 中尝试的几个配置:

1。仅使用pug-loader
{
    test:path.resolve('./html/index.pug'),
    type:'asset/resource',
    loader:'pug-loader',
    generator:{filename:'index.html'}}
}

这将创建一个 dist/index.html 文件,其中包含以下内容:

var pug = require("!../node_modules/pug-runtime/index.js");

function template(locals) {var pug_html = "", pug_mixins = {}, pug_interp;pug_html = pug_html + "\u003C!DOCTYPE html\u003E\u003Chtml lang=\"en\"\u003E\u003Chead\u003E\u003Ctitle\u003E" + (pug.escape(null == (pug_interp = "Hello World") ? "" : pug_interp)) + "\u003C\u002Ftitle\u003E\u003C\u002Fhead\u003E\u003Cbody\u003E\u003Cp\u003EHello World\u003C\u002Fp\u003E\u003C\u002Fbody\u003E\u003C\u002Fhtml\u003E";;return pug_html;};
module.exports = template;

看起来pug-loader 将 pug 文件转换为 JavaScript 模块,该模块在调用时生成 html 代码。我想要的是生成的 HTML 代码,而不是生成它的 JS 函数。

2。使用val-loader执行上面生成的JavaScript模块
{
    test:path.resolve('./html/index.pug'),
    type:'asset/resource',
    use:['val-loader','pug-loader'],
    generator:{filename:'index.html'}}
}

这也不起作用:Webpack 在尝试构建 dist/index.pug 时抛出错误:

ERROR in ./html/index.pug
Module build failed (from ./node_modules/val-loader/dist/cjs.js):
Error: Unable to execute "/home/bluenebula/work/webpack5-test/html/index.pug": Error: Cannot find module '!../node_modules/pug-runtime/index.js'

请注意,/home/bluenebula/work/webpack5-test/node_modules/pug-runtime/index.js 确实存在。

问题

  1. 资产模块是使用 Webpack 5 从 Pug 生成 HTML 文件的正确工具吗?

  2. 我还能做什么?

  3. 如何让它工作?

【问题讨论】:

标签: javascript webpack pug webpack-5 pug-loader


【解决方案1】:

是的,使用pug-plugin,您可以将 PUG 模板直接从 Webpack 条目渲染到 HTML 文件中。

npm install pug-plugin --save-dev

webpack.config.js 的工作示例

const PugPlugin = require('pug-plugin');
module.exports = {
  output: {
    path: path.join(__dirname, 'dist/'), // output path
    publicPath: '/', // must be defined a real publicPath
  },
  entry: {
    'index': 'html/index.pug', // output to dist/index.html

  },
  plugins: [
    new PugPlugin(), // support zero config and has options
  ],
  module: {
    rules: [
      {
        test: /\.pug$/,
        loader: PugPlugin.loader,
      },
    ],
  },
};

pug-pluginoptions,可以在哪里定义:

  • sourcePath 模板路径
  • outputPath 可以不同于 webpack.options.output.path
  • filename template stringFunction
  • postprocess渲染出来的纯HTML可以在这个函数中处理

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-24
    • 2021-12-24
    • 1970-01-01
    • 2018-04-14
    • 2020-01-15
    • 2022-11-03
    • 1970-01-01
    • 2019-11-12
    相关资源
    最近更新 更多