浏览器环境下的模块导入导出
特点
- 遵循
ES Module
规范。 - 导入导出方式:
- 导出:
export
和export default
。 - 导入:
import
。
- 导出:
详细导入导出方式
普通导入导出:
// module.js export function func1() {}; export const num1 = 999; // import.js import { func1, num1 } form './module.js' // module.js function func1() {}; const num1 = 999; export { func1, num1 } // import.js import { func1, num1 } form './module.js'
默认导出:
// module.js export default function () {} // import.js import func1 form './module.js' func1();
避免命名冲突:
// module.js function func1 () {}; export { func1 as funcName }; // import.js import { funcName } from './module.js'; // module.js function func1 () {}; export { func1 }; // import.js import { func1 as funcName } from './module.js';
创建模块对象:
// module.js function func1() {}; function func2() {}; export { func1, func2 }; // import.js import * as func form './module.js'; func.func1(); func.func2();
模块与类:
合并模块:
动态加载模块:
注意事项
- 导入模块的路径一般为,以站点作为根目录的绝对路径,但是通常可以使用点语法(表示当前路径)来找到所需的模块,这样就不需要写下整个路径。
- 在一些模块系统中可以省略文件扩展名,但是原生
JavaScript
模块系统并不支持。 - 模块导出的是引用,而不是副本,所以改变模块中的值是会影响所有引用该模块的功能。
NodeJS环境下的导入导出
特点
- 遵循
CommonJS
规范。 - 导入导出方式:
- 导出:
mudule.exports
和exports
两种方式。 - 导入:
require
。
- 导出:
- 第一次加载会运行整个模块,然后将结果缓存到内存中,之后加载这个模块是在缓存中读取。
- 模块加载的顺序是按照其在代码中出现的顺序。