export 和 import 常用技巧

export

  • 基本的两种用法:
export function foo() {
// ..
}
export var awesome = 42;
var bar = [1,2,3];
export { bar };
function foo() {
// ..
}
var awesome = 42;
var bar = [1,2,3];
export { foo, awesome, bar };
  • 导出的时候重命名:
function foo() { .. }
export { foo as bar };
  • 默认导出,每个模块只能有一个默认导出:
function foo(..) {
// ..
}
export default foo;
export{ foo as default };
  • 混合默认导出和普通的导出:
function foo() { .. }
function bar() { .. }
function baz() { .. }
export { foo as default, bar, baz, .. };
  • 从其他模块导出:
export { foo, bar } from "baz";
export { foo as FOO, bar as BAR } from "baz";
export * from "baz";

import

import { foo } from "foo";
foo();
import { foo as theFooFunc } from "foo";
theFooFunc();
import foo from "foo";
// or:
import { default as foo } from "foo";
export default function foo() { .. }
export function bar() { .. }
export function baz() { .. }

import FOOFN, { bar, baz as BAZ } from "foo";
FOOFN();
bar();
BAZ();
export function bar() { .. }
export var x = 42;
export function baz() { .. }

import * as foo from "foo";
foo.bar();
foo.x; // 42
foo.baz();

import有一个hoisted的过程,和var声明变量一样:

foo();
import { foo } from "foo";

你可能感兴趣的:(javascript,node,js,import,export)