什么是将“ module.exports” js文件迁移到.ts的最佳方法

时间:2019-06-05 11:08:56

标签: typescript

我看到了很多将.js迁移到.ts的示例,但我仍然不了解什么是最好的迁移模块的方法。

示例:

'use strict';

module.exports = class Ticker {
  private time: any;

  constructor(lookbacks) {
    this.time = lookbacks;
  }
};

谢谢

1 个答案:

答案 0 :(得分:2)

您想将内容移动到ES Modules

没有一种有趣的方式来自动移动所有内容,但是幸运的是,TypeScript还支持旧的module.exports =语法,因此您可以随意迁移。

ES模块的要点:

// a.js

module.exports = class Foo {}

// b.js
module.exports.one = 1;
module.exports.two = true;
module.exports.three = function three() {};
module.exports.four = class Four {};

// c.js
const Foo = require('./a');
const { one, two, three, four } = require('./b');
// or 
// const bModule = require('./b');
// bModule.three();

成为

// a.ts
export default class Foo {}

// b.ts
export const one = 1;
export const two = true;
export function three() {};
export class Four {}

// c.ts
import Foo from './a';
import { one, two, three, four } from './b';
// or
// import * as bModule from './b';
// bModule.three();

注意事项:

  • TypeScript具有自己的模块和ECMAScript规范之前的模块和导出系统(export = somethingimport x = require()),您不应在新项目中使用它们。
  • TypeScript具有“命名空间”的概念,以支持使用IIFE和命名对象来模拟模块的旧模式,您不应在新项目中使用它们。
  • module.exports = whateverexport default whatever并非严格等效,您必须重构所有module.exports以及相应的require()调用。