我是ES6的新手,对导出和导入类的方式有点困惑.似乎许多不同的符号是有效的,但工作方式不同.
我在src / web-api.js中写了这样一个类:
- class WebApi {
- // ...
- }
- export { WebApi };
我导入的是:
- import { WebApi } from './src/web-api.js'
这工作正常,但在我尝试相同的事情之前没有花括号,它没有工作:
- export WebApi; // Tells me '{' expected
- import WebApi from './src/web-api.js'; // No Syntax error but WebApi is undefined
即使在MDN documentation for export上,符号输出表达式;似乎是有效的.
同样,这就是我的应用程序文件中导入React的方式:
- import React,{ Component } from 'react';
为什么一个类和另一个没有大括号?一般来说,我怎么知道何时使用而不是使用花括号?
解决方法
ES6提供了许多通过导入/导出来管理模块的方法.但基本上有两个主要策略:
>默认导出/导入带有导出默认值和导入模块来自’./module’
>多个导出/导入,导出和导入{member}来自’./module’或导入*作为模块来自’./module’
(两者都可以混合但不推荐.)
模块导出/导入
- function foo() {
- console.log('Foo');
- }
- function bar() {
- console.log('Bar');
- }
策略#1:默认导出/导入
导出(module.js)
- function foo() {
- console.log('Foo');
- }
- function bar() {
- console.log('Bar');
- }
- export default {foo,bar};
- /*
- {foo,bar} is just an ES6 object literal that could be written like so:
- export default {
- foo: foo,bar: bar
- };
- It is the legacy of the "Revealing Module pattern"...
- */
导入(main.js)
- import module from './module';
- module.foo(); // Foo
- module.bar(); // Bar
策略#2:多次出口/进口
导出(module.js)
- export function foo() {
- console.log('Foo');
- }
- export function bar() {
- console.log('Bar');
- }
导入(main.js)
- import {foo,bar} from './module';
- foo(); // Foo
- bar(); // Bar
- /*
- This is valid too:
- import * as module from './module';
- module.foo(); // Foo
- module.bar(); // Bar
- */
正如我之前所说,ES6模块比这复杂得多.有关详细信息,我建议您阅读Axel Rauschmayer博士的探索ES6,特别是本章:http://exploringjs.com/es6/ch_modules.html.