【问题标题】:String substitution when strings are externalized to a separate file字符串外部化到单独文件时的字符串替换
【发布时间】:2017-11-08 14:40:32
【问题描述】:

我已经从我的代码中提取了所有字符串并将它们放入一个名为constants.ts ..的文件中。

export class Constants {
  public static API_URL = '/api/';
  public static CREATE_CHILD_API_URL = Constants.API_URL + '%s' + '/create-child';
}

我可以使用 console.log 将值替换为字符串:

import { Constants } from '../common/constants';
console.log(Constants.CREATE_CHILD_API_URL, 'dummyId');

在控制台中生成:/api/dummyId/create-child,这是目标。

我怎样才能做到这一点,但将结果存储在一个变量中以备后用?

有没有什么我可以使用的原生的并且可以在现代浏览器上运行而无需拉入库的东西?

Template literals 似乎不适合用例,因为变量不会在我的常量文件中定义。

【问题讨论】:

    标签: javascript typescript string-substitution


    【解决方案1】:

    你最终会用这种方法犯错误。我宁愿建议使用具有某些参数的函数,这些函数将通过在内部执行字符串插值来生成您需要的字符串:

    export class Urls {
      public static API_URL = '/api/';
      public static CREATE_CHILD_API_URL =
          (id: string) => `${Urls.API_URL}${id}/create-child`;
    }
    

    以后你就可以像这样使用它了:

    import { Urls } from '../common/urls';
    const forLaterUse = Urls.CREATE_CHILD_API_URL('dummyId');
    console.log(forLaterUse);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-19
      • 2017-09-04
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      • 1970-01-01
      • 2016-09-22
      相关资源
      最近更新 更多