ES6模块化
什么是模块化
目标:让一个.js文件(A.js)中可以引用另一个.js文件(B.js)中的代码
模块: 就是一个文件。
模块化的规范:
- commonjs 规范。nodejs中是commonjs规范。
- es6规范。ECMAScript规范。
在nodejs中,模块化规范:CommonJS
- 导出:
module.exports = '导出的内容'
exports.xxx = '导出的内容'
- 导入:
const path = require('path')
nodejs中的模块化与es6中的模块化是不同的。
ES6模块化
ES6也提供了模块化规范:ES6模块
- 默认导入与导出
- 导出:
export default 导出内容
- 导入:
import 变量名 from 'js模块路径'
- 导出:
- 按需导入与导出
- 导出:
export const 成员变量名1 = '导出内容1'
export const 成员变量名2 = '导出内容2'
- 导入:
import {成员变量名1} from 'js模块路径'
- 导出:
基本步骤
定义模块
- 创建一个.js文件,其中,写一些变量,函数…
// 创建一个模块
// 如何把es6module/a.js中的fn这个函数给main.js中去使用?
const a = 100
function fn(x,y) {
return x + y
}
导出模块
// 创建一个模块
// 如何把es6module/a.js中的fn这个函数给main.js中去使用?
// const a = 100
function fn(x,y) {
return x + y
}
// 导出模块中的fn
export {
fn }
导入模块
main.js
import {
fn } from './es6module/a.js'
console.log(fn(100,200)) // 300
默认导入与导出
module-a.js
// 模块a 默认导出
// 可以导出任何格式的内容:字符串 数字 函数 对象 数组 ...
export default {
name: '模块A',
attr: '属性'
}
main.js
import obj from './module-a'
console.log(obj) // {name: "模块A", attr: "属性"}
按需导入与导出
module-b.js
// 模块B 按需导出
export function fn(x,y) {
return x + y
}
export function fn1(x,y,z) {
return x + y +z
}
export const a = 314
另一种写法:
function fn(x,y) {
return x + y
}
function fn1(x,y,z) {
return x + y +z
}
const a = 314
export {
fn, fn1, a}
main.js
// 按需导入
import {
a,b} from './module-b'
console.log(a,b)
整体导入
// 按需导入(全部成员导入)
import * as all from './module-b'
console.log(all) // 收集了所有成员的变量(对象)
默认导出和按需导出共存
module-c.js
// 混合导入
// 同时有默认导出和 按需导出
const fn = function(x,y) {
return x + y
}
const a = 100
const fn1 = function(x,y,z) {
return x + y+z
}
// 按需导出
export {
a, fn1
}
// 默认导出
export default {
fn
}
main.js
// 有混合导入
import obj, {
fn1} from './es6module/c.js'
console.log(obj,fn1)
导入导出重命名
一个名字在a.js中导出也是这个名字;
在main.js中也有一个名字与之重复了,此时就要改名字:
- 在a.js中导出时改下名字
- 在main.js中导入时改下名字
export {
xxx as 新名字}
import {
xxx as 新名字}
// tool.js
const fn = function(x,y) {
return x + y
}
// 导出重命名
export {
fn as f2}
// index.js
import {
f2 as f1} from "./tool.js"
如有不足,请多指教,
未完待续,持续更新!
大家一起进步!