如何使TypeScript生成CommonJS有效模块? [英] How to make TypeScript generate a CommonJS valid module?

查看:153
本文介绍了如何使TypeScript生成CommonJS有效模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在TypeScript中有一个模块:

Let's say I have a module in TypeScript:

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

当我运行 tsc 生成上述代码时,尝试通过Node.js(纯JavaScript)导入生成的代码:

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`

使其工作的唯一方法是在 require()之后使用 .default ,这不是我想要的:

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.

如何使TypeScript生成一个输出,稍后将该输出用作Node.js模块(因为我将包发布到NPM中)而没有该 .default 属性?就是这样:

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

先谢谢了.:)

推荐答案

简短回答

使用 export = 构建可导出函数的CommonJS模块.

Short Answer

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

TypeScript文档说:

TypeScript支持 export = 来建模传统的CommonJS和AMD工作流程... export = 语法指定从模块导出的单个对象.这可以是类,接口,名称空间,函数或枚举.

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.

完整设置

myModule.ts

Full Setup

myModule.ts

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

tsconfig.json

tsconfig.json

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

myModule.js(输出)

myModule.js (output)

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

demo.js(用法)

demo.js (usage)

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

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

这篇关于如何使TypeScript生成CommonJS有效模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆