代码之家  ›  专栏  ›  技术社区  ›  Vitaliy Yanchuk

导入ES6样式,如*但用于常量集以避免重复[重复]

  •  0
  • Vitaliy Yanchuk  · 技术社区  · 7 年前

    目前,我有如下代码:

    import { actionA, actionB, actionC } from './someModule'
    doStuff({actionA, actionB, actionC})
    

    您可以看到,列出操作时存在重复,这是我的担忧,我希望在列出操作时避免重复。所以我想要这样的东西:

    import { actionA, actionB, actionC } as actions from './someModule'
    doStuff(actions)
    

    //someModule。js看起来像:

    export const actionA = ...
    export const actionB = ...
    export const actionC = ...
    export const actionD = ...
    ... and so on
    

    我不需要全部,因为可能还有更多与当前工作无关的东西需要导入

    1 回复  |  直到 7 年前
        1
  •  2
  •   fyasir    7 年前

    更新

    我在这篇文章中解释了同样的主题 post . 同上。

    根据 MDN documentation ,您可以在整个模块内容上设置别名,例如 * as constants 或单个内容,如 b as constants . 但不能对特定内容设置别名。因此,解决方案之一就是使用*。

    import * as constants from './module1';
    

    另一个可能的解决方案是通过 { a, c } 默认情况下。

    //module1.js
    
    export const a = ...
    export const b = ...
    export const c = ...
    export const d = ...
    export default { a, b, c };
    
    /module2.js
    import contants from './someModule';
    doStuff(constatns);
    

    最后,如果不想将这些常量作为默认值传递,可以创建一个对象并传递该对象。

    //module1.js
    
    export const a = ...
    export const b = ...
    export const c = ...
    export const b = ...
    export const myCustomConstants = { a, c };
    
    //module2.js
    import { myCustomConstants } from './someModule';
    doStuff(myCustomConstants);