繁体   English   中英

Webpack 简单地将一堆 Pug 模板编译为 HTML

[英]Webpack to simply compile a bunch of Pug templates to HTML

我开始使用 webpack,但我终生无法解决的一件事是如何获取一个充满 .pug 模板的文件夹(可能包含嵌套文件夹),然后将它们简单地编译为 static html 并将它们放入 output 文件夹中,为源模板文件夹中的每个 output html 文件维护任何嵌套文件夹结构...

我不想手动指定每个 individual.pug 文件,我绝对不希望 webpack 尝试将 .pugs 解析为 JS,然后尝试在 pug 文件中要求/导入任何 imgs/fonts 等,然后抱怨关于它,我刚刚完成了一个基本的 static 1:1 编译,pug 文件输入,html 文件输出。 为什么这么难做到?

使用 pug pug-html-loader将 .pug 转换为 .html 文件。 使用file-loader将文件复制到所需位置。 不要使用html-loader因为您不想处理生成的文件使用的资源。

你最终会在你的加载器规则中得到这样的东西(未经测试,webpack 1 语法,你可能需要为 webpack 2 调整它)

{
    test: /\.pug$/,
    loaders: ['file-loader?name=[path][name].html', 'pug-html-loader?pretty&exports=false']
}

接下来你需要在你的入口文件中引入你所有的 pug 文件

function requireAll (r) { r.keys().forEach(r); }
requireAll(require.context('./', true, /\.pug$/));

这可以通过 html-webpack-plugin 和 pug-loader 非常简单地完成。

webpack.config.js

const HTMLWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  // No javascript entrypoint to evaluate. Let the plugin do the heavy lifting
  entry: {},
  // Translate Pug to HTML
  module: { rules: [ { test: /\.pug$/, use: 'pug-loader' } ] },
  // Save HTML to file
  plugins: [ new HTMLWebpackPlugin({ template: './src/index.pug' }) ]
};

./src/index.pug

doctype html
html(land="en")
  head
    include path/to/another.pug
...

https://extri.co/2017/05/23/using-htmlwebpackplugin-and-pug/获得此信息,您还可以像通常使用 html-webpack-plugin 一样进一步导入 css 和 javascript。

尝试使用pug-plugin将 pug 模板编译成静态 HTML 文件:

webpack.config.js

const path = require('path');
const PugPlugin = require('pug-plugin');

module.exports = {
  output: {
    path: path.join(__dirname, 'public/'),
    publicPath: '/',
  },

  entry: {
    index: './src/pages/index.pug', // ==> public/index.html
  },

  plugins: [
    new PugPlugin(), // add the plugin
  ],

  module: {
    rules: [
      {
        test: /\.pug$/,
        loader: PugPlugin.loader, // add the pug-loader
      },
    ],
  },
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM