Export & Import用法總結

歡迎關注個人公衆號睿Talk,獲取我最新的文章:
clipboard.pngjavascript

1、前言

最近在作React組件庫升級的時候,發現之前這種舊的import方式不能用了:java

import zent from 'zent';

const {Input, Notify} = zent;

要改爲這種形式:segmentfault

import {Input, Notify} from 'zent';

究其緣由,是組件庫的export方式改變了。舊版本是這樣export的:工具

const zent = {
    Input, 
    Notify,
    ...
};

export default zent;

而新版本是這樣的:spa

export {
    Input, 
    Notify,
    ...
};

2、知識點

Export支持2種方式,一種是 Named export(新版組件庫),另外一種是 Default export(舊版組件庫)。設計

使用 Named export能夠在import的時候指定子模塊:code

import {Input, Notify} from 'zent';

而使用Default export在import的時候只能引用模塊總體:ip

import zent from 'zent';

後續使用子模塊時再作解構:get

const {Input, Notify} = zent;

另外,Named export 還有另一種形式:it

export const getAllDepts = () => {...};

export const getCurDept = () => {...};

export const getHeadquarter = () => {...};

也能夠在使用的時候指定須要的子模塊:

import {getAllDepts, getCurDept} from 'util'

若是在 Name export 中也使用 export default:

export const getAllDepts = () => {...};

export const getCurDept = () => {...};

export const getHeadquarter = () => {...};

export default getCurDept;

當 import 時不指定子模塊,就會默認加載 default 子模塊。

3、設計原則:

當模塊有多個獨立功能,能夠分拆使用的時候(如工具類模塊),應使用 Named export 的方式。當模塊只包含一個獨立的總體(如React組件),則使用 Default export 的方式。

相關文章
相關標籤/搜索