Search code examples
promisegulprollupjs

How do I mix promises and pipe in gulp?


In my project I compile multiple bundles from source files in nested directories using rollup.

I had a gulpfile with the following code, which worked fine:

function build_app_js(file, name) {
  return gulp.src(file)
    .pipe(sourcemaps.init())
    .pipe(rollup({format:'iife'}))
    .pipe(terser())
    .pipe(rename(name + '.js'))
    .pipe(rename({suffix: '.min'}))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(js_apps_dir))
}
// call the above for multiple sets of file+app_name

But then I changed one of the dependencies in my ES6 code which I accessed by relative path into an npm package, so it is now in node_modules. Rollup needs a plugin to resolve this, so I changed the above to this:

   .pipe(rollup({plugins: [resolveNodeModules()], format:'iife'}))

However this simply does not work.

I consulted rollup's docs on gulp, and adapted the example to my case, so it now looks like this:

function build_app_js(file, name) {
  return rollup.rollup({
    input: file,
    plugins: [
      resolveNodeModules()
    ]
  }).then(bundle => {
    return bundle.write({
      file: js_apps_dir + '/' + name + '.js',
      format: 'iife',
      sourcemap: true
    });
  });
}

This works, but has no minification step, and I don't know how to add one.

More generally, this is a totally different paradigm from using pipe(), and I do not know how to make both work together.

Do I try to add minification in the Promise syntax, or do I wrap the Promise function in such a way that I can use it with pipe?


Solution

  • Answering own question after 8 days.

    Minification can be achieved via rollup plugins, such as rollup-plugin-terser.

    You just need to be careful with how you import them:

    var rollup = require('rollup');
    var resolveNodeModules = require('rollup-plugin-node-resolve');
    //var terser = require('rollup-plugin-terser'); // WRONG
    var {terser} = require('rollup-plugin-terser'); // CORRECT
    
    function build_app_js(file, name) {
      return rollup.rollup({
        input: file,
        plugins: [
          resolveNodeModules(),
          terser()
        ]
      }).then(bundle => {
        return bundle.write({
          file: js_apps_dir + '/' + name + '.js',
          format: 'iife',
          sourcemap: true
        });
      });
    }
    

    If you import it the wrong way, you will get a terser() is not a function type error, which is because it will have imported terser as a module.

    It's a bit annoying that different rollup-plugins can't be imported the same way, but hey.