jpls93
jpls93

Reputation: 614

Gulp.js - Output files with variable directory names but with a constant filename

Given the following input files in src/, how do I output the files on the dist/ folder?

Project
+-- src
|   a.md
|   b.md
+-- dest
|   a/index.html
|   b/index.html

// Gulpfile.js
const gulp = require('gulp');
const md = require('gulp-markdown');

gulp.task('md', () => {
  return gulp.src('src/**/*.md')
    .pipe(md())
    .pipe(gulp.dest( // help ))
})

I think this is not a duplicate of Gulp.js - Use path from gulp.src() in gulp.dest(). That question deals with variable directory names and variable filenames. This question deals with variable directory names but with a constant filename.

Upvotes: 0

Views: 752

Answers (2)

Wilmer SH
Wilmer SH

Reputation: 1417

Using gulp-if:

Run

npm install gulp-if --save-dev

Your task

// Gulpfile.js
const gulp = require('gulp');
const md = require('gulp-markdown');
const gulpif = require('gulp-if');

gulp.task('md', () => {
  return gulp.src('src/**/*.md')
    .pipe(md())
    .pipe(gulpif('a.md', gulp.dest('dest/a')))
    .pipe(gulpif('b.md', gulp.dest('dest/b')));
})

Alternative

Using the else part of gulp-if, shorter but less readable

gulp.task('md', () => {
  return gulp.src('src/**/*.md')
    .pipe(md())
    .pipe(gulpif('a.md', gulp.dest('dest/a'), gulpif('b.md', gulp.dest('dest/b'))));
})

Upvotes: 0

Ananth Rao
Ananth Rao

Reputation: 1252

Try using the gulp-rename plugin https://www.npmjs.com/package/gulp-rename

You could use a function for name mapping:

const rename = require('gulp-rename');

...

gulp.task('md', () => {
  return gulp.src('src/**/*.md')
    .pipe(md())
    .pipe(rename((path) => {
      path.dirname += "/" + path.basename;
      path.basename = "index";
    })
    .pipe(gulp.dest('dest'))
})

Upvotes: 3

Related Questions