Search code examples
htmlgulppug-loader

Gulp: How can I build filename.pug to filename/index.html


Now I'm using gulp-pug

gulp.task('html', function(){
    return gulp.src(['src/**/*.pug', ...ignorePug])
        .pipe(pug())
        .pipe(gulp.dest('build'))
});

How can I build my HTML, so that file names are folder names.

Example:

src/index.pug -> build/index.html
src/team.pug -> build/team/index.html
src/somepage.pug -> build/somepage/index.html

Solution

  • Update

    I've published an npm package and gulp plugin here to address this exact issue: https://www.npmjs.com/package/gulp-url-builder


    Original Answer

    I had the same desire and wrote a function that uses gulp-rename to rewrite the file paths as they're being processed.

    After you run pug(), run rename() with this function:

    // custom pathbuilder function
    const pathbuilder = (path) => {
        if ('index' !== path.basename) {
            path.dirname = path.basename.split('_').join('/')
            path.basename = 'index'
        }
    }
    
    gulp.task('html', function(){
        return gulp.src(['src/**/*.pug', ...ignorePug])
            .pipe( pug() )
            .pipe( rename((path) => { pathbuilder(path) }) )
            .pipe( gulp.dest('build') )
    })
    

    It's set up to do what you're looking for. Additionally, you can use underscores to go deeper in directories.

    src/index.pug          -> build/index.html
    src/team.pug           -> build/team/index.html
    src/team_alexander.pug -> build/team/alexander/index.html
    src/somepage.pug       -> build/somepage/index.html
    

    Be sure to install and require the rename package first.