Can I have multiple entry points using Rollup with Gulp?

velvetkevorkian picture velvetkevorkian · Feb 17, 2018 · Viewed 9.1k times · Source

I have a gulpfile.js that uses Rollup to build two distinct JS files (front-end and admin). The rollup.config.js method allows multiple entry points and bundles to be specified, but to achieve this with Gulp I've had to do a bit of a nasty workaround.

const javascripts = [
  {
    src: './app/assets/javascripts/main.js',
    dest: './public/javascripts/main.js',
    moduleName: 'main'
  },
  {
    src: './admin/assets/javascripts/admin.js',
    dest: './public/admin/javascripts/admin.js',
    moduleName: 'admin'
  }
]

gulp.task('js:compile', ()=> {
  javascripts.forEach((item)=> {
    return rollup({
      input: item.src,
      plugins: [
        builtins(),
        nodeResolve({ jsnext: true, browser: true }),
        commonjs({
          include: 'node_modules/**',
          exclude: 'node_modules/rollup-plugin-node-globals/**',
          ignoreGlobal: false,
          sourceMap: true,
          main: true,
          browser: true
        }),
        json(),
        buble()
      ]
    }).then(function (bundle) {
      return bundle.write({
        format: 'iife',
        name: item.moduleName,
        file: item.dest
      })
    })
  })
})

Is there a better way of achieving this? I'm not averse to reorganising my files to use globbing or something similar.

EDIT: I've updated it to use Node's fs rather than having to specify each script but this still feels a bit clunky to me.

gulp.task('js:compile', () => {
  fs.readdir('./app/assets/javascripts', (err, files) => {
    if(err) throw err

    files.forEach((file) => {
      if(!file.match('.js')) return false

      return rollup({
        input: `./app/assets/javascripts/${file}`,
        plugins: [
          builtins(),
          nodeResolve({ jsnext: true, browser: true }),
          commonjs({
            include: 'node_modules/**',
            exclude: 'node_modules/rollup-plugin-node-globals/**',
            ignoreGlobal: false,
            sourceMap: true,
            main: true,
            browser: true
          }),
          json(),
          buble()
        ]
      }).then((bundle) => {
        return bundle.write({
          format: 'iife',
          name: file.split('.')[-2],
          file: `./public/javascripts/${file}`
        })
      }).catch( (e) => console.log(e) )
    })
  })
})

Answer

Dino Reic picture Dino Reic · May 15, 2019

Now, you can just return an array of objects from rollup.config.js.

So if you

  • need to compile a single file, return the object export default {...}
  • need to compile multiple files, return list of objects export default [{...},{...},{...}, ...]

Look here for inspiration