【问题标题】:Export all constants from files into index.ts and then export those constants as keys of an object?将文件中的所有常量导出到 index.ts 中,然后将这些常量导出为对象的键?
【发布时间】:2021-11-29 07:35:29
【问题描述】:

我有一个常量库,其中包含许多文件,例如以下结构:

#1 索引.ts

#2 src/

  • contact.ts
    • const first = [];
    • const second = [];
    • 常量第三 = [];
  • location.ts
    • const first = '';
    • const second = '';
    • const 第三 = '';

是否可以将每个文件中的所有常量导入和导出到index.ts,以便我可以导入到如下项目中:

// Imports: Constants
import { constants } from '@jeff/constants-library';

console.log(constants.contact.first);
console.log(constants.contact.second);
console.log(constants.contact.third);

从我的库文件中动态导出常量以便将其导入到我的项目中的最快/最有效的方法是什么?

【问题讨论】:

    标签: javascript typescript import constants export


    【解决方案1】:

    contactlocation 等文件中,您需要将所需的const 值标记为exports。模块是为封装而设计的,所以动态导出在这里并不是一个真正的选择。但是,只需添加关键字export

    export const first = [];
    

    之后,您可以创建一个自动导出和导入的constants-library.tsconstants-library/index.ts

    import * as foo from './foo';
    import * as bar from './bar';
    
    export const constants = { foo, bar };
    

    此时,假设您的@jeff 路径已设置,您的代码应该可以按预期工作:

    import { constants } from '@jeff/constants-library';
    
    console.log(constants.contact.first);
    

    请注意,这将在您的文件中包含所有的导出,因为 TypeScript 无法判断您想要或不想要哪些常量——它只知道您列出了哪些导出。作为替代方案,您可以使用对象简写将它们捆绑到单个 export 中,而不是单独导出所有 consts。

    // in contact.ts and location.ts
    export constants = { first, second, third };
    
    // in constant-library.ts or constant-library/index.ts
    import { constants as contact } from './contact';
    import { constants as location } from './location';
    
    export constants = { contact, location };
     
    

    【讨论】:

      猜你喜欢
      • 2020-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 2012-07-21
      • 2013-02-23
      • 2017-03-26
      • 1970-01-01
      相关资源
      最近更新 更多