How to make TypeScript generate a CommonJS valid module?

安稳与你 提交于 2021-01-28 01:50:31

问题


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

Thanks in advance. :)


回答1:


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!


来源:https://stackoverflow.com/questions/56402067/how-to-make-typescript-generate-a-commonjs-valid-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!