mbrc
mbrc

Reputation: 3953

What is best aproach to migrate "module.exports" js file to .ts

I saw many examples how to migrate .js to .ts but I still don't knopw what is best aproach to migrate module.

Example:

'use strict';

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

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

Thank you

Upvotes: 0

Views: 178

Answers (1)

Madara's Ghost
Madara's Ghost

Reputation: 174947

You want to move things to ES Modules.

There's no fun way to automatically move everything, but lucky for you, TypeScript supports the old module.exports = syntax as well, so you can migrate at your leisure.

The main points of ES Modules:

// 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();

Becomes

// 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();

Things to know:

  • TypeScript has its own module and exports system from before the ECMAScript specs had one (export = something and import x = require()), you should not use them in new projects.
  • TypeScript has a concept of "namespace" to support the old patterns of using IIFEs and named objects to emulate modules, you should not use them in new projects.
  • module.exports = whatever and export default whatever are not strictly equivalent, you have to refactor all of the module.exports as well as the corresponding require() calls.

Upvotes: 2

Related Questions