问题
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... Theexport =
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