一个模块包含一个或多个js文件,一个模块中一般还包含一个package.json文件,该文件中包含了模块的配置信息,里面的配置信息有:
name 模块名称
version 模块版本
description 描述信息
main 指定模块入口文件
type 当type值为module的时候,支持es模块化
scripts 脚本,使用' npm run 脚本名'可以调用
dependencies 依赖关系
devDependencies 环境依赖或测试依赖
1.ES6模块化
1-module1.js
let fristName = 'ren'
let lastName = 'terry';
export { fristName, lastName }
console.log('这是module1模块')
2-module2.js
import './1-module1'
import { fristName, lastName } from './1-module1'
// es6 静态加载 编译时加载
console.log('module2打印', fristName, lastName)
这里通过两个文件来演示导入导出的过程
先转码 再运行
babel src --out-dir dist
node dist/module/2-module2.js
ES6导出的是一个接口,接口存放的是一个变量
2..CommonJS模块化
CommonJS 模块就是对象,输入时必须查找对象属性。
模块化对象
Node内部提供一个Module构建函数。所有模块都是Module的实例。每个模块内部,都有一个module对象,代表当前模块。它有以下属性。module.id 模块的识别符,通常是带有绝对路径的模块文件名。 module.filename 模块的文件名,带有绝对路径。 module.loaded 返回一个布尔值,表示模块是否已经完成加载。 module.parent 返回一个对象,表示调用该模块的模块。 module.children 返回一个数组,表示该模块要用到的其他模块。 module.exports 表示模块对外输出的值。
//nodejs模块导出
let firstname = 'ren';
let lastname = 'terry';
// module.exports.firstname = firstname;
module.exports = {
firstname: firstname,
lastname: lastname
};
// Nodejs模块导入
let { firstname, lastname } = require('./module3');
console.log(firstname, lastname);
console.log(module.id);
console.log(module.filename);
console.log(module.loaded);
console.log(module.parent);
console.log(module.children);
上述描述的是Commonjs模块化导入导出的过程
3.ES6模块与CommonJS模块的差异
这里总结一下它们的差异:
1、CommonJS 模块输出的是一个值的拷贝/复制,ES6 模块输出的是值的引用。
2、CommonJS 模块是运行时加载,ES6 模块是编译时输出接口。