简体   繁体   English

如何导出在全局范围内可用于ES6导入的模块

[英]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 . 这样做的好处是默认导出是一个ReactCrop函数。 Meaning that when it's globally included via a <script> tag then window.ReactCrop is what you expect. 这意味着,当通过<script>标记全局包含它时,则期望window.ReactCrop

However if I change it to ES6: 但是,如果我将其更改为ES6:

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

It's exported as an object. 它作为对象导出。 Which makes eslint and typescript happier. 这使eslint和打字稿更快乐。 Otherwise you have to: 否则,您必须:

import * as ReactCrop from...

To make babel convert it to an object, as it stands this won't work: 要使babel将其转换为对象,按原样,这将不起作用:

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. 也就是说,用户必须执行window.ReactCrop.ReactCrop才能访问该类。

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? 问题:如何满足这两种情况,以使全局范围仍然是一个函数,因为window.ReactCrop.ReactCrop是总值,但是允许{ partialImports }并让eslint和打字稿满意,因为他们找到了默认导出的对象?

PS I'm using webpack to export like so: PS我正在使用webpack导出,如下所示:

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. 我不认为有一个webpack选项可以在导出为全局文件时自动执行此操作。

because window.ReactCrop.ReactCrop is gross 因为window.ReactCrop.ReactCrop是总值

You can use window.ReactCrop.default instead. 您可以改用window.ReactCrop.default

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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