import,export深入理解

export

最正常:

    var firstName = 'Michael';
    var lastName = 'Jackson';
    var year = 1958;
    export { firstName, lastName, year };

输出函数或类:

    export function multiply(x, y) {
      return x * y;
    };

重命名:

    function v1() { ... }
    function v2() { ... }
    
    export {
      v1 as streamV1,
      v2 as streamV2,
      v2 as streamLatestVersion
    };

动态改变输出的值:

    export var foo = 'bar';
    setTimeout(() => foo = 'baz', 500);
    //上面代码输出变量foo,值为bar,500 毫秒之后变成baz。

多个输出,import

// circle.js
export function area(radius) {
  return Math.PI * radius * radius;
}
export function circumference(radius) {
  return 2 * Math.PI * radius;
}


import * as circle from './circle';

console.log('圆面积:' + circle.area(4));
console.log('圆周长:' + circle.circumference(14));

export和export default

理解:
    1.export的时候,单个变量输出,可以import变量({area}或者* as circle(circle为对象))
    2.export default的时候,相当于导出的整个对象,所以不用括号,可以对象.属性(直接定义对象名circle(对象))
// 第一组
export default function crc32() { // 输出
  // ...
}

import crc32 from 'crc32'; // 输入

// 第二组
export function crc32() { // 输出
  // ...
};

import {crc32} from 'crc32'; // 输入


第一组是使用export default时,对应的import语句不需要使用大括号;
第二组是不使用export default时,对应的import语句需要使用大括号。

export default命令用于指定模块的默认输出。显然,一个模块只能有一个默认输出,因此export default命令只能使用一次。所以,import命令后面才不用加大括号,因为只可能唯一对应export default命令。

// 正确
export var a = 1;

// 正确
var a = 1;
export default a;
上面代码中,export default a的含义是将变量a的值赋给变量default。

import

导入组件中的部分对象

import { stat, exists, readFile } from 'fs';

导入整个对象

import fs from 'fs';
使用的时候
fs.stat
fs.exists
fs.readFile

导入对象重命名

import { lastName as surname } from './profile.js';

import命令输入的变量都是只读的

import命令具有提升效果,会提升到整个模块的头部,首先执行

foo();

import { foo } from 'my_module';
//不会报错

仅仅执行lodash模块,但是不输入任何值.代码加载了两次lodash,但是只会执行一次。

import 'lodash';
import 'lodash';
posted @ 2020-02-07 11:36  未月廿三  阅读(756)  评论(0编辑  收藏  举报