15

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

1 Answer 1

13

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!
Sign up to request clarification or add additional context in comments.

2 Comments

why tsc can not convert "export default" to "export =" ? It is weird.
They're not the same

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.