ES6+ javascript 模块导出选项 [英] ES6+ javascript module export options

查看:12
本文介绍了ES6+ javascript 模块导出选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到 ES6 模块的公共导出以以下两种方式完成:

I've seen public exports of ES6 modules done in both of the following ways:

// method 1
export var getAnswer = function () { return 'forty two'; };

// method 2
export default function () { return 'forty two'; };

  1. 这两个都有效吗?
  2. 如果是,为什么它们都存在?
  3. 对于使用 ES6 语法的模块导出,还有其他有效的选项吗?

我很惊讶我的 googlefu 无法找到答案.我关注 ES6 模块,CommonJS、RequireJS、AMD、Node 等

I'm surprised I haven't been able to find the answer with my googlefu. I'm concerned only with ES6 modules, not CommonJS, RequireJS, AMD, Node, etc.

推荐答案

一年多以后,这里是我找到的关于该主题的最佳信息.

A year and some later, here is the best information I've found on the subject.

有 4 种导出类型.以下是每种用法的用法示例,以及使用它们的一些导入:

There are 4 types of exports. Here are usage examples of each, along with some imports that use them:

// default exports
export default 42;
export default {};
export default [];
export default (1 + 2);
export default foo;
export default function () {}
export default class {}
export default function foo () {}
export default class foo {}

// variables exports
export var foo = 1;
export var foo = function () {};
export var bar;
export let foo = 2;
export let bar;
export const foo = 3;
export function foo () {}
export class foo {}

// named exports
export {};
export {foo};
export {foo, bar};
export {foo as bar};
export {foo as default};
export {foo as default, bar};

// exports from
export * from "foo";
export {} from "foo";
export {foo} from "foo";
export {foo, bar} from "foo";
export {foo as bar} from "foo";
export {foo as default} from "foo";
export {foo as default, bar} from "foo";
export {default} from "foo";
export {default as foo} from "foo";

导入语法

// default imports
import foo from "foo";
import {default as foo} from "foo";

// named imports
import {} from "foo";
import {bar} from "foo";
import {bar, baz} from "foo";
import {bar as baz} from "foo";
import {bar as baz, xyz} from "foo";

// glob imports
import * as foo from "foo";

// mixing imports
import foo, {baz as xyz} from "foo";
import foo, * as bar from "foo";

// just import
import "foo";

来源.

这篇关于ES6+ javascript 模块导出选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆