Michał Sadowski
Michał Sadowski

Reputation: 2149

gulp.dest with glob gulp.src - making it relative

I have a simple task in gulp that is supposed to transpile js:

function js() {
  return gulp.src('lib/modules/*/source/js/*.js')
    .pipe(babel({
      presets: ['@babel/env']
    }))
    .pipe(gulp.dest((fileVinyl) => {
      return fileVinyl.path.replace('/source/', '/public/').replace(/[^\/]*js$/, '')
    }))
}

exports.default = gulp.parallel(js)

And I have a file structure like this:

lib
- modules
  - module1
    - source
      - js
        - file.js
  - module2
    - source
      - js
        - file.js
  - moduleN (...)

Now, I want it to create files like this:

lib
- modules
  - module1
    - public
      - js
        - file.js
    - source (...)
  - module2
    - public
      - js
        - file.js
    - source (...)
  - moduleN (...)

Of course, the code above doesn't work, it outputs files to folders like lib/modules/module1/public/js/module1/source/js/. Is there any method to force gulp to output the file to a specified path instead for it treating it like a base path for appending its own ideas?

Upvotes: 1

Views: 573

Answers (2)

Michał Sadowski
Michał Sadowski

Reputation: 2149

The issue I had here was the wrong base for the file. But as I needed to change it dynamically, I couldn't just set it up in src options. Fortunately, I could change it easily in dest function, where I have the path available:

 .pipe(gulp.dest((fileVinyl) => {
      //changing the base so that it will include the whole path to the file,
      //excluding the filename
      fileVinyl.base = fileVinyl.path.replace(/[^\/]*js$/, '')

      //outputing the file to a /public/ folder instead of /source/,
      //keeping the structure
      return path.relative(process.cwd(), fileVinyl.path.replace('/source/', '/public/').replace(/[^\/]*js$/, ''))
    }))

Upvotes: 2

Amir
Amir

Reputation: 1905

use the option base in gulp.src

like this:

gulp.src('your_file.js', {base: 'your_base_path'})
.pipe(/*...*/)

in your case, the base should be lib/modules

like this:

gulp.src('lib/modules/**/*.js', {base: 'lib/modules'})
.pipe(/*...*/)
.pipe(gulp.dest('lib/modules'))

this will create what you want:

lib
- modules
  - module1
    - public
      - js
        - file.js

This option tells gulp to ignore the base part of path and treat the rest of path as relative and hence replicate it in dest

Upvotes: 1

Related Questions