「这是我参与2022首次更文挑战的第19天,活动详情查看:2022首次更文挑战」。
在上篇文章中,我们介绍了ES Module的基本使用JavaScript模块化总结(四)。在本篇文章,我们来学习下其他的导入导出方式。
export导出的其他方式
在上篇文章中,我们使用的导出方式是export后面直接跟声明语句。
export const name = 'haha'
export const age = 18
第二种导出方式是export导出和声明语句分开。将所有需要导出的标识符,放到export后面的{}中。注意:这里的{}里面不是ES6的对象字面量的增强写法,也不是表示一个对象的。因此,export {name: name}是一个错误的写法。
const name = 'haha'
const age = 18
function foo() {
console.log('foo');
}
export {
name,
age,
foo
}
第三种导出方式是在第二种导出方式基础上给标识符起一个别名,目的是在导入的时候不和原有的标识符起冲突,需要注意的是,在导入的时候我们需要使用导出时起得别名。第一种和第二种导出方式比较常用,第三种导出方式不常用,我们通常会在导入的时候起别名。
export {
name as fName,
age as fAge,
foo as fFoo
}
import导入的其他方式
在上篇文章中,我们使用的是普通的导入方式。import {标识符列表} from '模块';
import {name, age, foo} from './foo.js'
第二种导入方式是导入时给标识符起别名。
import {name as fName, age as fAge, foo as fFoo} from './foo.js'
第三种导入方式是将导出的所有内容放到一个标识符中,可以防止标识符的命名冲突。
import * as foo from './foo.js'
console.log(foo.name);
console.log(foo.age);
foo.foo()
const name = 'xixi'
console.log(name);
以上3种导入方式都是比较常用的。
export和import结合使用
在项目中,我们通常会封装工具库,里面放一些工具函数,然后在其他文件中导入这些工具函数。
我们新建一个utils文件夹,并且在文件夹中新建format.js和math.js,按照之前的做法,我们进行导出和导入。
在format.js文件中导出
function timeFormat() {
return '2022-2-9'
}
function priceFormat() {
return '22.22'
}
export {
timeFormat,
priceFormat
}
在math.js文件中导出
function add(num1, num2) {
return num1 + num2
}
function sub(num1, num2) {
return num1 - num2
}
export {
add,
sub
}
在main.js中导入,导入时不能省略.js后缀,因为是在浏览器环境运行,不是在webpack环境,webpack环境会自动补充文件后缀。
import {timeFormat, priceFormat} from './utils/format.js'
import {add, sub} from './utils/math.js'
我们通常不会使用如上的导入导出方式。
通常我们会这样做。在utils文件中新建index.js文件,我们可以看到很多的库,例如axios会有一个统一的出口。
import {timeFormat, priceFormat} from './format.js'
import {add, sub} from './math.js'
export {
timeFormat,
priceFormat,
add,
sub
}
然后在main.js中进行导入。
import { timeFormat, priceFormat, add, sub } from './utils/index.js'
上述写法太繁琐了。
方式二,在index.js中
export {timeFormat, priceFormat} from './format.js'
export {add, sub} from './math.js'
方式三,导出全部。
export * from './format.js'
export * from './math.js'