我正在尝试将js文件转换为ts。但是从构造函数返回配置时会抛出错误。这是我正在转换js-> ts的正确方法。另外我如何更改import语句。 PFB我的代码:
这是原始的js文件,正在导入为
let caasConfig = require('../config/caasConfig.js')(process.env.NODE_ENV);
//////////////////// caasConfig.js//////////
module.exports = function getConfig(environment) {
let config = {
defaultContentPath: 'default/project/Us',
urgentContentPath: 'urgent/project/R',
defaultContentId: 'default',
urgentContentIdSuf: 'urgentcontent',
contactInfo: 'contactinfo/project/CCD',
contactInfoSele: 'contactinfoselection/project/RC'
};
if (environment === 'local' || environment === 'development') {
config.domainPath =
'https://xyz/rs/cf//rest/public/content/pageid/';
} else {
config.domainPath =
'https://xyz/rs/cf/content-adapter-webservice-production-current/';
}
return config;
};
caaSConfig.ts :(我转换的方式)
export class getConfig {
environment: any;
constructor(environment) {}
if (environment === 'local' || environment === 'development') {
config.domainPath =
'https://xyz/rs/cf//rest/public/content/pageid/';
} else {
config.domainPath =
'https://xyz/rs/cf/content-adapter-webservice-production-current/';
}
return config;
};
}
config = {
defaultContentPath: 'default/project/Us',
urgentContentPath: 'urgent/project/R',
defaultContentId: 'default',
urgentContentIdSuf: 'urgentcontent',
contactInfo: 'contactinfo/project/CCD',
contactInfoSele: 'contactinfoselection/project/RC'
};
// the way I'm importing this in another file:
import {caasConfig}(process.env.NODE_ENV) from '../config/caasConfig';
如果您正在重写它,那么只需将该函数导出为命名导出。
export function getConfig(environment: string) {
const config = {
defaultContentPath: 'default/project/Us',
urgentContentPath: 'urgent/project/R',
defaultContentId: 'default',
urgentContentIdSuf: 'urgentcontent',
contactInfo: 'contactinfo/project/CCD',
contactInfoSele: 'contactinfoselection/project/RC'
};
if (environment === 'local' || environment === 'development') {
config.domainPath =
'https://xyz/rs/cf//rest/public/content/pageid/';
} else {
config.domainPath =
'https://xyz/rs/cf/content-adapter-webservice-production-current/';
}
return config;
};
然后就可以像...那样使用它
import { getConfig } from '../config/caasConfig';
编辑:
如果为返回定义类型,它可能会帮助其他人:
export interface Config {
defaultContentPath: string;
urgentContentPath: string;
defaultContentId: string;
urgentContentIdSuf: string;
contactInfo: string;
contactInfoSele: string;
domainPath: string;
}
然后将您的功能更新为:
export function getConfig(environment: string): Config {
这种方式当你使用它时你可以做类似......
import { getConfig, Config } from '../config/caasConfig';
class SomeClass {
private config: Config;
constructor() {
this.config = getConfig('development');
}
}