Rollup bundle using exports instead of module.exports

Viewed 624

I have a library I am bundling using rollup and this is a section from the rollup.config.js file:

export default {
  input: `src/${libraryName}.ts`,
  output: [
    { file: pkg.main, name: camelCase(libraryName), format: 'cjs', sourcemap: true },
    { file: pkg.module, format: 'es', sourcemap: true },
  ],

  ....
}

It generates two files dist/libname.umd.js and dist/libname.es5.js. I have confirmed from putting a console.log statement in both the files that using require('libname') loads the dist/libname.umd.js. However, the following line:

var x = require('libname').X
console.log(x) // This is undefined

prints undefined. So, I tried to edit the dist/libname.umd.js file manually and at the bottom of the file I saw:

exports.X = X;

with the overall variable X being bundled somewhere above in the file. I modified this to:

module.exports.X = X;

and then it seems to work. I am a bit new to node/js so I wasn't sure if it this is the way to be exporting modules, but on reading a blog post (http://www.hacksparrow.com/node-js-exports-vs-module-exports.html) it turns out both of them should be fine? I am still a bit unclear on this one though.

Also, when I simply did this:

console.log(require('libname')

it prints [Function: uniqSetWithForEach] and console.log(require('libname')()) prints [].

EDIT So for the time being, just so that I can continue my work I have modified rollup.config.ts to add an outro:

export default {
  ...
  output: [
      { file: pkg.main, name: camelCase(libraryName), format: 'cjs',
        sourcemap: true,
        outro: 'module.exports = Object.assign({}, module.exports, exports)'
      }
  ]
  ...
}

and this seems to do it for now, but I'm pretty sure it's not a clean solution.

0 Answers
Related