Reputation: 66355
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',
}
Upvotes: 2
Views: 1343
Reputation: 664513
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.
Upvotes: 3