【问题标题】:Typescript optional import only if existTypescript 可选导入仅在存在时
【发布时间】:2020-12-09 16:33:56
【问题描述】:

我在我的 Angular 应用程序中使用 npm 包 git-ref-sync 生成一些 git 信息到一个名为 ../environments/git-version 的文件。

在我的组件中,我以这种方式导入生成的东西:

import { gitVersion } from '../../environments/git-version';

但有时这个文件还没有生成,那么是否有可能只有在存在的情况下才导入这个文件?

【问题讨论】:

    标签: angular git typescript import


    【解决方案1】:

    你可以使用import语句,它是一个Promise。

    // example git-version.ts includes
    // export const gitVersion = '1.1.1';
    // here
        import('../git-version').then(
          result => console.log('gitVersion is ', result.gitVersion)
        ).catch(
          () => console.info('git-version does not exist yet!'),
        );
    

    https://stackblitz.com/edit/angular-ivy-xwrvqn?file=src%2Fapp%2Fapp.component.ts

    【讨论】:

    • 这样不行,如果你删除了git-version.ts文件,那么就会出现编译错误,因为它不存在。
    • 好吧,你是对的!您还可以考虑将文件作为资产提供并使用 http 模块加载它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 2023-01-08
    • 2021-11-04
    • 2016-12-17
    相关资源
    最近更新 更多