我已经从我的代码中提取了所有字符串并将它们放入一个名为 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
这是目标。
除了将结果存储在变量中供以后使用外,我怎样才能做同样的事情?
有没有我可以使用的东西,它是 native 的并且可以在现代浏览器上运行而无需引入库?
Template literals
似乎不适合用例,因为变量不会在我的常量文件中定义。
最佳答案
使用这种方法你最终会犯错误。我宁愿推荐使用带有某些参数的函数,这些参数将通过在内部执行字符串插值来生成您需要的字符串:
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);
关于javascript - 将字符串外部化到单独文件时的字符串替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47182499/