持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第3天,点击查看活动详情
\
Module
CommonJS模块本质是通过 require 获取类对象再在对应对象上获取相应方法或属性。这种加载方式“运行时加载”,因为只有运行时才能得到这个对象,导致完全没办法在编译时做“静态优化”。
import 的加载方式是在运行时完成的。在编译时就完成模块加载,效率要比 CommonJS 模块的加载方式高
所以建议开发中全部使用esmodule导入导出,不要使用require形式。
as 重命名
export default 不能跟表达式 export default var a = 1; // 报错
export {
name1 as newName1,
name2 as newName2,
function1 as newfunction1
};
import { name3 as newName3 } from './file.js';
import { testFun1, testFun2 } from './part.js';
// * 导入所有
import * as partA from './part.js';
// partA.testFun1 partA.testFun2
export { es6 as default } from './someModule';
// 等同于
import { es6 } from './someModule';
export default es6;
如果要使用的常量非常多可以专门建一个constants目录使用的时候直接导出
export const FORM_LAYOUT = {
labelCol: { span: 10 },
wrapperCol: { span: 19 },
colon: false,
};
export const AAAType = {
AAAType_Button: 1001, // type 1
AAAType_Label: 1002, // type 2
AAAType_Children: 1003, // type 3
};
条件加载
if (condition) {
import('moduleA').then(console.log).catch(console.log);
} else {
import('moduleB').then(console.log);
}
-
模块化的几个概念
- babel: 将es6转换为es5的, babel转换后的代码是遵循commonJS规范的 而commonJS规范是node的语法规范,浏览器则不支持
- webpack 将commonJS规范转换为浏览器能识别的代码
es6->es5(commonJS规范)->浏览器可执行代码
从 v13.2 版本开始,Node.js 已经默认打开了 ES6 模块(ESModule)支持 .mjs文件总是以 ES6 模块加载,.cjs文件总是以 CommonJS 模块加载,.js文件的加载取决于package.json里面type字段的设置。
总结
-
使用
import取代require, 使用export取代module.exports -
优先使用解构赋值。
const [first, second] = arr;
// bad way
function getFullName(user) {
const firstName = user.firstName;
const lastName = user.lastName;
}
// good way
function getFullName(obj) {
const { firstName, lastName } = obj;
}
// best way
function getFullName({ firstName, lastName }) {
}
- 使用 rest 不在函数中使用arguments数组
function funName(a, b, ...others) {
}
funName("1", "2", "3", "4");
- 使用默认值语法设置函数参数的默认值。
// bad
function handleThings(opts) {
opts = opts || {};
}
// 推荐使用
function handleThings(opts = {}) {
// ...
}