【问题标题】:Gulp: How to compile multiple .pug files into several index.html files inside foldersGulp:如何将多个 .pug 文件编译成文件夹内的多个 index.html 文件
【发布时间】:2021-10-06 21:20:42
【问题描述】:

我正在学习使用 gulp,我决定使用 pug 来编写我所有的 html。

事情是有这个文件夹结构:

src/pug
├── base
│   ├── mixins.pug
│   └── variables.pug
├── components
│   ├── footer.pug
│   ├── header.pug
│   ├── head.pug
│   └── template.pug
├── index.pug
└── views
    └── about.pug

我希望 gulp 忽略所有不是 index.html 的文件以及我在 views 文件夹中的所有文件。

我正在使用此配置进行此操作:

function compilePug() {
  return src(['./src/pug/index.pug','./src/pug/views/*.pug'], {base: './src/pug/'})
  .pipe(pug().on("error", console.log))
  .pipe(
    pug({
      // Your options in here.
    })
  )
  .pipe(dest('./dist/'));
};

问题是,就像这样创建和输出dist/views/about.html

但我宁愿生成类似 dist/about/index.html 的内容。这样我可以在多个页面之间导航,而无需在末尾添加 .html 扩展名。

这可能吗?

【问题讨论】:

    标签: gulp pug


    【解决方案1】:

    我编写了一个 npm 模块来执行此操作:gulp-url-builder

    首先,将您的index.pug 移动到您的views 目录中。您想要呈现为页面的所有内容都应该放入其中。不要忘记调整模板的任何 extends 路径。

    src/pug
    ├── base
    │   ├── mixins.pug
    │   └── variables.pug
    ├── components
    │   ├── footer.pug
    │   ├── header.pug
    │   ├── head.pug
    │   └── template.pug
    └── views
        ├── about.pug
        └── index.pug
    

    在您的 gulpfile 中安装所需的 url 构建器模块后,您可以修改您的 compilePug() 函数,使其看起来像这样:

    const { src, dest, series, parallel, watch } = require('gulp')
    const pug = require('gulp-pug')
    const urlBuilder = require('gulp-url-builder')
    
    function compilePug() {
      return src([
        './src/pug/views/*.pug'
      ]).pipe( pug() )
        .pipe( urlBuilder() )
        .pipe( dest('dist') )
    }
    

    这会根据这个模式输出html文件(注意下划线可以用于嵌套页面):

    src/pug/views/index.pug        --> dist/index.html
    src/pug/views/about.pug        --> dist/about/index.html
    src/pug/views/foo-bar.pug      --> dist/foo-bar/index.html
    src/pug/views/blog.pug         --> dist/blog/index.html
    src/pug/views/blog_my-post.pug --> dist/blog/my-post/index.html
    

    【讨论】:

    • 非常感谢肖恩。我真的很感激你的回答有多好。我的意思是,这是一个非常棒的解决方案,非常适合我。
    猜你喜欢
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-03
    • 2016-09-04
    相关资源
    最近更新 更多