1. CommonJS
module.exports和exports
// 使用module.exports
// a.js
var s = 'i am ronffy'
module.exports = s;
console.log(module);
// b.js
var a = require('./a.js'); // a --> i am ronffy
// 使用exports
// a.js
var s = 'i am ronffy'
exports = s;
// b.js
var a = require('./a.js'); // a --> {}
// 说明:module.exports 是真正导出的对象(也是require接收的对象),而 exports 只是 module.exports 的一个引用。当将 exports 变量重新指向一个新的对象时,与module.exports不在引用同一个对象,并不会改变 module.exports 的引用
/* var module = {
exports: {}
}
var exports = module.exports;
console.log(module.exports === exports); // true
var s = 'i am ronffy'
exports = s; // module.exports 不受影响
console.log(module.exports === exports); // false */
// 改写exports
// a.js
exports.s = 'i am ronffy';
// b.js
var a = require('./a.js');
console.log(a.s); // i am ronffy
2. ES6 module
导出接口
// 方式一
export const prefix = 'https://github.com';
export const api = `${prefix}/ronffy`;
// 方式二
const prefix = 'https://github.com';
const api = `${prefix}/ronffy`;
export {
prefix,
api,
}
// 方式三:默认导出
// foo.js
export default function foo() {}
// 等同于:
function foo() {}
export {
foo as default
}
// 方式四:先导入再导出简写
export { api } from './config.js';
// 等同于:
import { api } from './config.js';
export {
api
}
导入接口
// 方式一
import { api } from './config.js';
// or
// 配合`import`使用的`as`关键字用来为导入的接口重命名。
import { api as myApi } from './config.js';
// 方式二:整体导入
import * as config from './config.js';
const api = config.api;
// 方式三:默认导出的导入
// foo.js
export const conut = 0;
export default function myFoo() {}
// index.js
// 默认导入的接口此处刻意命名为cusFoo,旨在说明该命名可完全自定义。
import cusFoo, { count } from './foo.js'; //cusFoo可以自定义导入对象的名称
// 等同于:
import { default as cusFoo, count } from './foo.js';
// 方式四:整体加载
import './config.js';
// 方式五:动态加载模块(按需加载)
function foo() {
import('./config.js')
.then(({ api }) => {
});
}
const modulePath = './utils' + '/api.js';
import(modulePath);
3. CommonJS 和 ES6 module
CommonJS 和 AMD 是运行时加载,在运行时确定模块的依赖关系
ES6 module 是在编译时(import()是运行时加载)处理模块依赖关系