在学习Vue时,对各种JS模块的导入与导出的方式感到困惑,简单总结如下:
一、导出与导入方式
方式1:
- 导出:JS中使用
export default {需要导出的模块名}
- 导入:
- HTML中在script标签中使用
import 自定义总模块名称 from JS文件位置
- script标签必须增加
type="module"
来声明这个脚本是一个模块,否则会报错。
- HTML中在script标签中使用
test.js
中代码:
let helloWorld=function () {
console.log("Hello Vue");
}
let test= function () {
console.log("test Vue ");
}
let name = 'Vue'
export default {
helloWorld, //需要导出的模块1
test, //需要导出的模块2
name //需要导出的模块3
}
test.html
代码:
<script type="module">
import justNameIt from './module.js' //justNameIt为自定义名称
console.log(justNameIt.name) //Vue
justNameIt.helloWorld() //Hello Vue
</script>
方式2:
- 导出:JS中使用
export 模块名
- 导入:
- HTML中在script标签中使用
import {模块1,模拟2...} from JS文件位置
- script标签必须增加
type="module"
来声明这个脚本是一个模块,否则会报错。
- HTML中在script标签中使用
test.js
中代码:
export function helloWorld() {
console.log("Hello Vue");
}
export function test() {
console.log("test Vue ");
}
export let name = "Vue"
test.html
代码:
<script type="module">
import { helloWorld, test, name } from './module.js'
helloWorld() //Hello Vue
test() //test Vue
console.log(name) //Vue
</script>
二、避免模块命名冲突:
对导出的模块进行重命名import { helloWold as 新名称} from JS文件位置
总结:两者使用上几无差别, 方式1倾向全部导出,方向2倾向按需部分导出
参考: JavaScript modules 模块