0
点赞
收藏
分享

微信扫一扫

JS ES6中export 和 import详解

40dba2f2a596 2022-03-30 阅读 147

JS ES6中export 和 import详解


文章目录


前言

在学习Vue的时候,import/export是必不可少的。假如我们写了一个单页面组件A,而在另一个文件B里面需要用到它,这时候就要用ES6的 import/export语法,在文件A 中定义输出接口 export,在文件B中引入 import 把引用的组件用起来,


一、export default

importDefault.js使用import命令时,需要知道所要加载的变量名或函数名,否则无法加载,这时候在模块文件 exportDefalut.js 中就需要用到 export default / export

使用 export default

exportDefalut.js

// 默认输出一个函数
// 第一种 一个js文件只允许一个 export default
export default function (){
  console.log('foo');
}

importDefault.js

// 可以用任意名称指向 exportDefalut.js 输出的方法,
// 第一种 引入 不需用 {} 大括号
import name from './exportDefalut.js'
name()

使用 export

exportDefalut.js

// 第二种 使用 export ,引用时加 {}
export const str = 'hello world'
export function f(a){
console.log(1)
}

importDefault.js


// 第二种 引入加 {}
import {str,f} from './exportDefalut.js'
举报

相关推荐

ES6 import

0 条评论