ES6模組

weixin_34116110發表於2019-01-04

模組的優點

在模組頂部建立的變數不會自動被新增到全域性共享作用域。

匯出

匯出方式一

export const PI = 3.14;

export const obj = {
    name: 'lee',
    age: 18
}

export function sum (a, b) {
    return a+b;
}

匯出方式二

const obj = {
    name: 'lee',
    age: 18
}

const PI = 3.14;

function sum (a, b) {
    return a+b;
}

export {obj, PI, sum}

匯入

分別匯入

import {obj, PI, sum} from './file.js'
console.log(sum(1, 2)); // 3

匯入整個模組

import * as file from './file.js'
console.log(file.sum(1, 2)); // 3

重新命名

匯出重新命名

function sum (a, b) {
    return a+b;
}

export {sum as add}
import {add} from './file.js'

匯入重新命名

function sum (a, b) {
    return a+b;
}

export {sum}
import {sum as add} from './file.js'

預設值

匯出預設值

匯出預設值方式一
function sum (a, b) {
    return a+b;
}

export default sum;
匯出預設值方式二
function sum (a, b) {
    return a+b;
}

export {sum as default}

匯入預設值

import sum from './file.js'
匯出預設和非預設
export const PI = 3.14;
export default function sum (a, b) {
    return a+b;
}

預設必須排在非預設之前

import sum, {PI} from './file.js'

相關文章