es6的export和import
- export:在一个js模块文件中,export 可以导出很多变量,但是 export default 只能导出一个
- import:通过 export 导出的变量,需要用 import { } from 引入;通过export default 导出的变量使用 import 引入时不加 {}(import 是静态执行的,不能使用表达式)
import
和export
命令都只能在模块的顶层,即最外层,不能在代码块之中,否则会语法报错- 使用 export 导出变量时,必须要加 {} ;使用export default 导出时不用加 {};定义时就导出的话也不用加 {},如:
export var a = 'a';
// 导出方式 1
export var a = 'a';
export const b = 'b';
export function multiply(x, y) {
return x * y;
};
// 导入方式 1
import {a, b, multiply} from './test1.js' // 注意 {} 中的名字要与export中的变量名一致
// 导出方式 2
var a = 'a';
const b = 'b';
function fn1() { ... }
function fn2() { ... }
export {a, b};
export {fn1 as f1, fn2 as f2}; // 使用 as 可定义导出模块的别名
// 导入方式 2
import {a as a1, b, f1, f2} from './test2.js' // 同理 import 中也可使用 as
import * as test2 from './test2.js' // 也可导入 test2.js 模块文件中的所有对外接口
// 报错
export 1;
// 报错
var m = 1;
export m;
export {m}; // 不会报错
// 导出方式 3
export default function () { // 匿名函数
console.log('aaaaaa');
}
// 或者
export default function aaa() { // 具名函数
console.log('aaaaaa');
}
// 导入方式 3
import test3 from './test3.js'; // 使用 export default 导出时,在导入时,test3 可以是任意名字,不用与 函数名aaa 一样
// 导出方式 4
export default const testStr = 'testStr';
// 导入方式 4
import testStr from './test.js';
小剧场 之 import() 动态加载
上面也说了,import 是采用静态加载的方式,并且会提升到整个模块的头部,在编译阶段首先执行,所以不能实现模块按需加载。
import()
函数即可进行动态按需加载,并返回一个 promise 对象,即可用 .then 和 .catch 如:
// 在用户点击按钮时, 引入 test 模块
// 某 dom 元素的点击事件
clickFn() {
import('./test.js')
.then(testRes => {
testRes.open();
})
.catch(error => {
console.log(error);
})
}
// 使用 import() 实现条件加载
if (condition) {
import('moduleA').then(...);
} else {
import('moduleB').then(...);
}
import 和 require 的区别
-
export 和 import 是 ES6 的标准语法
-
module.exports(或者 exports )和 require 是 node 中引入npm包的CommonJS规范的语法(require 支持按需加载)
-
require 可以在任意地方引入,并且 module.exports 导出时是采用拷贝的方式。即当导出的值发生变化,导入的值也不会变化,如果想要更新值就要重新导入
-
export 和 import 是采用实时绑定的方式,即 导入的值会随着导出的值的变化而变化
// moudule.exports 导出一个对象 // test.js var firstName = 'Michael'; var lastName = 'Jackson'; var year = 1958; module.exports = { firstName, lastName, year }; // demo.js const test = require('./test.js'); console.log(test); // {firstName: "Michael", lastName: "Jackson", year: 1958} // exports 直接导出一个变量 (不太常用) var year = 1958; exports.year = year; // demo.js const test = require('./test.js'); console.log(test); // {year: 1958}
-
module.exports导出之后,后面的代码就会失效
// test.js module.exports = { firstName, lastName, year }; exports.name = '222'; // demo.js const test = require('./test.js'); console.log(test); // {firstName: "Michael", lastName: "Jackson", year: 1958} // 上面的 exports.name = '222'; 没有作用