简体   繁体   中英

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}

ie 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',
}

How can I satisfy both cases so that globally it's still a function

This is not possible if you use a namespace import. A namespace object never is a function.

You can however do

import ReactCrop, * as ReactCropNs from "…";
Object.assign(ReactCrop, ReactCropNs);
window.ReactCrop = ReactCrop;

if you want to make it available globally in that form. I don't think there's a webpack option to do this automatically when exporting as a global.

because window.ReactCrop.ReactCrop is gross

You can use window.ReactCrop.default instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM