将javaScript转换为typeScript以及如何导入该文件

时间:2019-04-08 20:21:15

标签: javascript typescript

我正在尝试将js文件转换为ts。但是从构造函数返回配置时会引发错误。这是我转换js-> ts的正确方法吗?另外,我该如何更改导入语句。 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';

1 个答案:

答案 0 :(得分:0)

如果要重写它,则只需将该函数导出为已命名的导出即可。

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');
  }
}