ES6模块化
概述
在 ES6 前, 实现模块化使用的是 RequireJS 或者 seaJS(分别是基于 AMD 规范的模块化库, 和基于 CMD 规范的模块化库)。
ES6 引入了模块化,其设计思想是在编译时就能确定模块的依赖关系,以及输入和输出的变量。
ES6 的模块化分为导出(export) @与导入(import)两个模块。
特点
ES6 的模块自动开启严格模式,不管你有没有在模块头部加上 use strict;。
模块中可以导入和导出各种类型的变量,如函数,对象,字符串,数字,布尔值,类等。
每个模块都有自己的上下文,每一个模块内声明的变量都是局部变量,不会污染全局作用域。
每一个模块只加载一次(是单例的), 若再去加载同目录下同文件,直接从内存中读取。
export 与 import
案例1
swiper.js 导出模块
class Swiper {
constructor(speed,direction){
this.speed = speed,
this.direction = direction
}
moveLeft(){
console.log('swiper向左运动,速度是'+ this.speed);
}
moveRight(){
console.log('swiper向右运动,速度是'+ this.speed);
}
}
// 导出模块
export default Swiper
main.js 引入模块
/**
* 需求
* 1. 创建swiper实例,实现轮播图
*/
//引入模块
import Swiper from './modules/swiper.js'
const mySwiper = new Swiper(300,'left')
mySwiper.moveLeft()
// 引入模块时可以自定义变量名
// import Slider from './modules/swiper.js'
// const mySwiper = new Slider(300,'left')
// mySwiper.moveLeft()
案例2
swiper.js
class Swiper {
constructor(speed,direction){
this.speed = speed,
this.direction = direction
}
moveLeft(){
console.log('swiper向左运动,速度是'+ this.speed);
}
moveRight(){
console.log('swiper向右运动,速度是'+ this.speed);
}
}
const config = {
baseUrl: 'http://localhost:5000',
timeout: 2000,
time: '2022-10-25'
}
// 导出模块
export default {
Swiper: Swiper,
config: config
}
main.js
import util from './modules/swiper'
const myswiper = new util.Swiper(250,'right')
myswiper.moveRight()
let url = '/flowerList'
console.log('请求地址为:' + util.config.baseUrl + url);
案例3
main.js 依赖swiper.js
swiper.js依赖util.js
util.js
function rnd(start,end){
return Math.floor(Math.random() * (end - start + 1)) + start
}
function getCookie(){
console.log('getCookie');
}
function getDate(){
console.log('getDate');
}
export default {
rnd,
getCookie,
getDate
}
swiper.js
import util from './util'
class Swiper {
constructor(speed,direction){
this.speed = speed,
this.direction = direction,
this.size = util.rnd(2,50)
}
moveLeft(){
console.log('swiper向左运动,速度是'+ this.speed, this.size);
}
moveRight(){
console.log('swiper向右运动,速度是'+ this.speed,this.size);
}
}
const config = {
baseUrl: 'http://localhost:5000',
timeout: 2000,
time: '2022-10-25'
}
// 导出模块
export default {
Swiper: Swiper,
config: config
}
main.js
import util from './modules/swiper'
const myswiper = new util.Swiper(250,'right')
myswiper.moveRight()
let url = '/flowerList'
console.log('请求地址为:' + util.config.baseUrl + url);