【问题标题】:Writing a Node module in TypeScript for consumption by both TS and JS projects用 TypeScript 编写一个 Node 模块供 TS 和 JS 项目使用
【发布时间】:2018-04-06 10:05:50
【问题描述】:
我有一个用 TypeScript 编写的 Express 中间件项目。我想在基于 JS 和 TS 的 Node 项目中使用它。
我无法配置我的项目以确保
- 上游项目正在输出可供 Node 使用的模块
- 我的模块可以在
myGreatFunction = require('myGreatFunction') // typeof = function格式的JS项目中使用
- 我的模块可以使用
import myGreatFunction from 'myGreatFunction' // typeof = function格式
- 我的模块没有被输出为带有 .default 的对象,而这不是预期的,反之亦然,但在确实预期的情况下没有输出。
感觉好像我只能实现其中一些目标,而不能实现其他目标。
TSConfig 属性(上游和下游)的正确咒语是什么,以确保如此?
最后我达成了妥协——见下文。
【问题讨论】:
标签:
node.js
typescript
commonjs
【解决方案1】:
图书馆
tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noEmitHelpers": true
},
}
module.ts:
export class MyClass {
static Version: string = "1.0";
}
当我们编译这个模块时,我们会得到:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var MyClass = /** @class */ (function () {
function MyClass() {
}
MyClass.Version = "1.0";
return MyClass;
}());
exports.MyClass = MyClass;
TS 客户端
client.ts:
import {MyClass} from "./../src/module";
console.log(MyClass.Version);
编译并运行node client.js - 见“1.0”
JS 客户端
只需从已编译的 ts 客户端 grad 相同的代码:
var module_1 = require("./../src/module");
console.log(module_1.MyClass.Version);
同样的输出
【解决方案2】:
-
在 typescript 中使用 typescript 文件。
Assuming B.ts is the typescript file that you want to use in A.ts, then:
import { B's module that are exported } from 'path/to/B'; // notice there is no extension mentioned here.
Also B must have a export module in it.
-
在js文件中使用ts文件。
B.ts = file which you want to use in your main file.
A.js = your main file.
In your A.js:
var external = require('path/to/B'); // notice there is no extension mentioned here.
【解决方案3】:
最后我妥协了:
库 TSConfig:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"declaration": true
}
}
图书馆:
export = function myGroovyFunction() {...}
下游项目,TypeScript
import * as myGroovyFunction from 'mygroovyfunction';
下游项目,JavaScript
const myGroovyFunction = require('mygroovyfunction');
TypeScript 导入没有我想要的那么简洁,但我可以处理。