Monday, 24 September 2018

How to export a module which works globally and for ES6 importing

Currently I'm exporting like this:

module.exports = ReactCrop;
module.exports.getPixelCrop = getPixelCrop;
module.exports.makeAspectCrop = makeAspectCrop;
module.exports.containCrop = containCrop;

Basically taking a class (function) and adding the non-default exports to it.

The advantage of this is that the default export is a function ReactCrop. Meaning that when it's globally included via a <script> tag then window.ReactCrop is what you expect.

However if I change it to ES6:

export {
  ReactCrop,
  ReactCrop as default,
  getPixelCrop,
  makeAspectCrop,
  containCrop,
};

It's exported as an object. Which makes eslint and typescript happier. Otherwise you have to:

import * as ReactCrop from...

To make babel convert it to an object, as it stands this won't work:

import { getPixelCrop } from... 

However when globally consuming the module it outputs this:

window.ReactCrop
{ReactCrop: ƒ, default: ƒ, getPixelCrop: ƒ, makeAspectCrop: ƒ, __esModule: true}

i.e. the user would have to do window.ReactCrop.ReactCrop to access the class.

Question: How can I satisfy both cases so that globally it's still a function because window.ReactCrop.ReactCrop is gross, but allow { partialImports } and keep eslint and typescript happy by them finding an object with a default export?

PS I'm using webpack to export like so:

output: {
  path: path.resolve('dist'),
  library: 'ReactCrop',
  libraryTarget: 'umd',
  filename: minified ? 'ReactCrop.min.js' : 'ReactCrop.js',
}



from How to export a module which works globally and for ES6 importing

No comments:

Post a Comment