ES6模块化简明笔记

1、什么是模块化

详见看上一篇笔记CommonJs模块化简明笔记

2、为什么需要模块化

详见看上一篇笔记CommonJs模块化简明笔记

3、导入和导出的概念

详见看上一篇笔记CommonJs模块化简明笔记

4、模块导出(暴露)

4.1 导出(暴露)方式1:分别暴露

export const name = '张三'
export const age = 18
export function getAddress (){
    
    
	return '甘肃省兰州市城关区'
} 

4.2 导出(暴露)方式2:统一暴露

const name = '张三'
const age = 18
function getAddress (){
    
    
	return '甘肃省兰州市城关区'
} 
export {
    
    name,age,getAddress}

统一导出,并非对象,所以无法使用xx:xx的格式

4.3 导出(暴露)方式3:默认暴露

const name = '张三'
const age = 18
function getAddress (){
    
    
	return '甘肃省兰州市城关区'
} 
// export default 默认暴露
export default {
    
    name,age,getAddress}

//默认暴露,引入的使用,比较简单,随意起名
import aaa from './user.js'
console.log(aaa)

5、模块导入

5.1 全部导入

可以将模块中的所有导出内容整合到⼀个对象中。
无论导出是什么方式

import * as user from './user.js' 

5.2 命名导入

分别导出统一导出的时候使用

import {
    
    name,age,getAddress} from './user.js' 

也可以在导入的时候重命名:

import {
    
    name as myName,age as myAge ,getAddress as myGetAddress} from './user.js' 

5.3 默认导入

import user from './user.js' //默认导出的名字可以修改,不是必须为user

5.4 动态导入

允许在运⾏时按需加载模块,返回值是⼀个 Promise。
在这里插入图片描述

5.5 import 可以不接收任何数据

例如:只是让 test.js 参与运⾏

import './test.js'

6、Node.js 中运⾏ ES6 模块

Node.js 中运⾏ ES6 模块代码有两种⽅式:

6.1 ⽅式⼀

将 JavaScript ⽂件后缀从 .js 改为 .mjs ,Node 则会⾃动识别 ES6 模块。
在这里插入图片描述

扫描二维码关注公众号,回复: 17453914 查看本文章

6.2 ⽅式⼆

在目录下新建package.json,如果有,就不需要新建了
在这里插入图片描述

package.json中添加配置,type 属性值为 module
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_48300767/article/details/141086375