早期js作为一种脚本语言,只是为了做一些简单表单验证或动画实现等,所以不需要模块化
Commonjs
在es6之前js都没有自己模块化方案,社区涌现三大模块化规范;AMD、CMD、commonJS。
没有模块化的缺点
没有模块前必须要用立即回调函数解决有可能命名冲突:
这种也是麻烦需要记住moduleA才能用到及后续才不会冲突
const moduleA = (function() {
let name = "why"
let age = 18
let height = 1.88
console.log(name)
return {
name,
age,
height
}
}())
commonJS细节
- Node支持cmmonJS、
- 普通js不支持commonJS(浏览器运行环境下< browseify插件支持浏览器编译commonJS >)、
- webpack也支持commonJS
commonJS变量
commonJS提供核心变量exports、module.exports、require
- require函数帮助我们导入其他模块(自定义模块、系统模块、第三方模块)的内容
- exports和module.exports负责对模块中的内容进行导出
eports
exports是一个对象
module.exports
module.exports跟exports一样的,真实开发主要用module.exports(且module才是模块导出的真正实现者,为什么exports也能实现导出,因为指向同一个引用)
module.exports = {
name,
age,
sayHello
}
require
三种情况
-
require(x) x是node的核心模块,直接返回核心模块,停止查找
-
require(路径)
- require(第三方模块)
ES module(import export)
ES Module是es6提供的(使用这个模块默认采用use strict),这个采用同源策略(同源策略需要http等协议,所以需要用服务器打开)
<script src="./main.js" type="module"></script>
export
- 在语句声明的前面直接加上export关键字
export const name = '123123'
- 将所有需要导出的标识符,放到export后面的 {}中(这种{}不代表是对象)
const name = '123'
const age = 12
export {
name,
age
}
- 导出时给标识符起一个别名
const name = '123'
const age = 12
export {
name as fullName,
age
}
import
- import {标识符列表} from '模块'
import {name} from './1.js'
- 导入时给标识符起别名
import {name as fullName} from './1.js'
- 通过 * 将模块功能放到一个模块功能对象(a module object)上
import add as addModule from './add.js'
export与import结合使用
把模块间接导出
export { add as addModule } from './add.js'
defalut默认导出
默认导出export时可以不需要指定名字,在导入时不需要使用 {},并且可以自己任意来指定名字,一个模块只能有一个默认导出
// add.js
export default function(){}
// b.js
import add from './add.js'
import()函数
普通import是需要放在js顶部,不能放在逻辑代码中,因为js引擎在解析时是需要知道模块依赖关系的
if(1){
import('./add.js').then(res=>{
console(res)
})
}
import.meta
import.meta是一个给JavaScript模块暴露特定上下文的元数据属性的对象
它包含了这个模块的信息,比如说这个模块的URL