ES6 导入与导出

164 阅读1分钟

1.环境准备(node.js)

1.打开目标文件夹, cmd 指令下

npm init  or npm init -y

2.新增 package.json 的 type 类型为 module

{
  "type": "module",
  "name": "export",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {}
}

3.准备两个文件夹,一个负责导出,一个负责导入

image.png

2.导出与导入操作

2.1.默认导出与导入

// ◆导出1: default 导出不能结构(默认导出)
export default {
    a: 1,
    b: 2,
    fn1: () => console.log('我是函数 fn1')
}
// ◆导入1: 默认导入(不能解构)
import obj from './01-导出.js'
console.log(obj)

2.2按需导出与导入

// ◆导出2: 单个定义后导出,必须解构导入(按需导出)
export let c = 3
export const d = 4
export function fn2() {
    console.log('我是函数 fn2')
}
// ◆导入2: 按需导入(必须解构)
import {c,d,fn2 as fn} from './01-导出.js'
console.log(c,d,fn) 

2.3不用导出数据,不用导入对象的导入导出

// ◆导出3: 不导出数据,就是实现具体功能
console.log('我不会导出数据')
// ◆导入3: 不需要导入对象,只需要具体功能
import  './01-导出.js'

3.终端 node 一下 ,查看打印效果

image.png

注意 ES6的导入,自定义前缀后缀不能省略