Luiz Felipe
Luiz Felipe

Reputation: 997

How to make TypeScript generate a CommonJS valid module?

Let's say I have a module in TypeScript:

export default function myModule(name: string): void {
  alert(`Hello, ${name}!`)
}

When I run tsc to build the above code, and try to import the generated code through Node.js (pure JavaScript):

const myModule = require('./dist/myModule.js')
myModule('Luiz') // ERROR! `myModule` is `undefined`

The only way to make it work is by using .default after the require(), which is not what I want:

//                                            ↓↓↓↓↓↓↓↓
const myModule = require('./dist/myModule.js').default
myModule('Luiz') // Now it works.

How can I make TypeScript generate an output that I can use later as a Node.js module (as I'm publishing the package into NPM) without that .default property? Just like this:

const myModule = require('my-module')

Upvotes: 13

Views: 16601

Answers (1)

Shaun Luttin
Shaun Luttin

Reputation: 141442

Short Answer

Use export = to build a CommonJS module that exports a function.

The TypeScript docs say:

TypeScript supports export = to model the traditional CommonJS and AMD workflow... The export = syntax specifies a single object that is exported from the module. This can be a class, interface, namespace, function, or enum.

Full Setup

myModule.ts

export = function myModule(name: string): void {
  console.log(`Hello, ${name}!`)
}

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs"
  }
}

myModule.js (output)

"use strict";
module.exports = function myModule(name) {
    console.log("Hello, " + name + "!");
};

demo.js (usage)

const myModule = require('./my-module');

myModule('Luiz'); // Hello, Luiz!

Upvotes: 11

Related Questions