JS ES6 中 export 及 export default 的区别

615 阅读2分钟

在 JavaScript ES6中,export 与 export default 均可用于导出常量、函数、文件、模块等,我们可以在其它文件或模块中通过 import 常量名/函数名/文件名/模块名 的方式,将其导入进行使用,但在一个文件或模块中,export、import 可以有多个,但 export default 有且仅有一个

使用 export

我们在 config.js 文件中配置了多个值,都想导出给vue页面使用,使用 export

// config.js
var name1 = "小明"
var name2 = "小明"
export { name1, mame2 }

export const str = "Hello world"
export function fun(n) {
    return n+1
}
export const list = [
    {
        title: 'PCT国际专利申请量',
        number: '20,209',
        unit: '件',
    },
    {
        title: '国家级高新科技企业数',
        number: '20,209',
        unit: '件',
    }
]

vue 页面对应的导入方式必须带花括号 {},而且花括号里的变量名必须与 config.js 文件中定义的变量名一致

import { name1, name2 } from 'config'

import { str } from 'config'
import { fun } from 'config'
import { list } from 'config'
或者
import { str, fun, list } from 'config'

使用export default

export default 这相当于起了一个系统默认的变量名 default,自然 default 只能有一个值,所以一个文件内不能有多个 export default,这个命令常用于指定模块的默认输出,即当前这个模块只能有一个默认输出,例如下面我们在 config.js 文件中使用 export default 只能导出一个值

// config.js
const list = [
    {
        title: 'PCT国际专利申请量',
        number: '20,209',
        unit: '件',
    },
    {
        title: '国家级高新科技企业数',
        number: '20,209',
        unit: '件',
    }
]
export default list

或者

// config.js
export default list = [
    {
        title: 'PCT国际专利申请量',
        number: '20,209',
        unit: '件',
    },
    {
        title: '国家级高新科技企业数',
        number: '20,209',
        unit: '件',
    }
]

vue 页面对应的导入方式不带花括号,而且 export default 相当于输出了一个叫 default 的变量,系统允许我们为其取任意名字,故 import 导入时可随意取名

import list from 'config'import xxoo from 'config'

注意事项

export default 与普通的 export 不要同时使用