CommonJS的核心思想是通过require方法来同步加载依赖的其他模块,通过module.exports到处需要暴露的接口。根据这个规范,每个文件就是一个模块,有自己的作用域。在一个文件里面定义的变量、函数、类,都是私有的,对其他文件不可见。
1、module.exports
// utils.js
let appid = '123456'
let bar = function (id) {
return `编号:${id}` }
// 通过module.exports将appid与bar暴露出去
module.exports = {appid , bar}
----------------------------------------------------
let utils = require('./utils') // 通过require引入utils
console.log(utils.appid) // 12345
console.log(utils.bar(2)) // 编号:2
2、exports
为了方便,Node为每个模块提供一个exports变量,指向module.exports。这等同在每个模块头部,有一行这样的命令。
let exports = module.exports;
!!! 这里要注意:
不能直接将exports变量指向一个值,因为这样等于切断了exports与module.exports的联系。
let appid = '123456'
// 错误写法
exports = {appid}
// 正确写法
exports.appid = appid
ES6模块规范
不同于CommonJS,ES6使用 export 和 import 来导出、导入模块。
3、export
// utils.js
export const appid = '123234'
export function getAppid() {
return '123456'}
-------------------------------------------------
// 导出的几种方式:
import { appid , getAppid } from './utils' // 导入多个导出
import * as utils from 'utils' // 作为命名空间导入整个模块
console.log(appid) // 123234
console.log(getAppid ()) // 123456
4、export default
使用export default命令,为模块指定默认输出,这里要注意错误的一种写法:
// 错误写法
export default const appid = '123456'
// 正确写法
const appid = '123456'
export default appid
----------------------------------------------------
import utils from './utils' // 导入默认值
console.log(utils) // 123456
顺便介绍一下import常用的几种写法:
import { foo, bar } from ‘./utils’ // 导入多个导出
import * as utils from ‘utils’ // 作为命名空间导入整个模块
import utils from ‘utils’ // 导入默认值
import utils , { foo , bar } from ‘./utils’ // 导入多个导出与默认导出
import { foo , bar } , * as utils from ‘utils’ // 导入命名空间整个模块与多个导出
import(’./utils’).then (res) => { // do something} // import动态导入函数,当使用它的时候,会返回一个promise。
let module = await import(’./utils’) // 支持await关键字