最近在做React组件库升级的时候,发现以前这种旧的import方式不能用了:
import zent from 'zent';
const {Input, Notify} = zent;要改成这种形式:
import {Input, Notify} from 'zent';究其原因,是组件库的export方式改变了。旧版本是这样export的:
const zent = {
Input,
Notify,
...
};
export default zent;而新版本是这样的:
export {
Input,
Notify,
...
};Export支持2种方式,一种是 Named export(新版组件库),另一种是 Default export(旧版组件库)。
使用 Named export可以在import的时候指定子模块:
import {Input, Notify} from 'zent';而使用Default export在import的时候只能引用模块整体:
import zent from 'zent';后续使用子模块时再做解构:
const {Input, Notify} = zent;另外,Named export 还有另外一种形式:
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 子模块。
当模块有多个独立功能,可以分拆使用的时候(如工具类模块),应使用 Named export 的方式。当模块只包含一个独立的整体(如React组件),则使用 Default export 的方式。