模块化类型
- 浏览器环境:ES Modules(export/import)
- NodeJs环境:Commonjs(module.exports/require)
ES Modules导出的并非一个对象,而是变量的引用
const name = 'xiaoming';const age = 18;const sex = 'man';// 导出export { name, age };// 别名导出// export { name as YourName, age as YourAge };// 默认导出// export default sex;---------------------// 导入import { name, age } from '...';// 导入别名import { YourName, YourAge } from '...';// 导入默认import sex from '...';
导入并直接导出默认对象
export { default as XXX } from '...';-------------------------------------- // 相当于import XXX from '...';export { XXX }
ES Modules基本特性
自动采用严格模式,忽略‘use strict’
<script type="module">console.log(this) // 由于ES Modules默认采用严格模式,严格模式下没有this,this打印undefined</script>
每个ES Modules模块都是单独的私有作用域
<script type="module">const name = 'xiaoming'</script><script type="module">console.log(name) // not defined</script>
ES Modules是通过CORS去请求外部JS模块,src地址需支持跨域
<script type="module" src="https://libs.baidu.com/jquery/2.0.0/jquery.min.js"> // 跨域报错</script>
ES Modules的script标签会延迟执行脚本
<script type="module">alert('dmeo')</script><p>页面内容</p> // 先显示页面内容,然后才会执行ES Modules中脚本
ES Modules in Nodejs 与Commonjs
ES Modules中可以导入Commonjs模块
- Commonjs中不能导入ES Modules模块
- Commonjs始终只会导出一个默认成员(对象) ```javascript module.exports = { foo: () => {} } // 相当于 exports.foo = () => {}
const mod = require(‘…’); console.log(mod) // {foo: () => {}} ```
- 注意import不是解构对象
