Gulp:如何将多个.pug文件编译成文件夹中的几个index.html文件

8e2ybdfx  于 2022-12-08  发布在  Gulp
关注(0)|答案(1)|浏览(142)

我正在学习使用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扩展名。
这可能吗?

to94eoyn

to94eoyn1#

我已经编写了一个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

相关问题