2.5 module.exports\exports\export\import用法

一、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(...)
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值