一、nodejs中
1、exports导出
a.新建test.js文件
const x = {
a:1,
b:2
}
const y = {
a:1,
b:2
}
function f(){
console.log(1)
}
exports.n = f
exports.m = {x,y}
b.新建index.js
const l =require('./test1.js')
console.log(l)
output://{ n: [Function: f], m: { x: { a: 1, b: 2 }, y: { a: 1, b: 2 } } }
//可以通过l.n()、l.m.x.a这种方式调用
module.exports.x 等同于exports.x
c.如果在test.js中使用module.exports = f,则index.js中的l等同于f,可以通过l()方式调用
d.如果使用exports = f,则在index.js中的l,其实是一个空对象
e.通过在test.js对module.exprots或exports.x不同的赋值方式,可以改变index.js中的引入的变量类型
module.exports = {f,x};
通过{}对module.exports赋值,则index.js中引入的l是一个对象
module.exports = [f,x];
通过module.exports = [f,x],则index.js中引入的l是一个数组
f.总结
exports.x等于module.exports.x
exports = x 导出的是一个空对象
module.exports = x 可以正常导出变量和方法
exports == module.exports
二、ES6中导出
1、export导出
导出变量
export var a= 1;
批量导出变量
var a= 1; var b= 2;
export {a, b,};
导出方法
export funcion f(x,y){
return x*y;}
批量导出
function a(){}
function b(){}
export {
a as x,
b as y
}
总结:
export后面如果不是跟着表达式的话,必须使用{}
export不能在代码块的作用域内
2、import导入
批量导入
import {a, b} from ''
别名导入
import { a as x } from '';
整体导入
import {* as y} from '';
总结:
import 后面不能使用变量和表达式
import会优先执行
导入的js文件后缀.js可以省略
3、export default
export default function () { console.log('a'); }
引用
import a from '';
a是别名,不用使用{},可以任意命名
4、import()
按需加载
if (condition) {
import('moduleA').then(...);
} else {
import('moduleB').then(...);
}
事件加载
button.addEventListener('click', event => {
import('moduleA')
.then(...)
});