node.js - 使用 TypeScript 撰寫 Node 模組,以供 TS 和 JS 專案使用
我有一個用 TypeScript 編寫的 Express 中介軟體專案。我希望在基於 JS 和 TS 的 Node 專案中使用它。
我在配置我的專案以確保...時遇到困難
- 上游專案正在輸出可被 Node 使用的模組
- 我的模組可以在 JS 專案中以以下格式使用:
myGreatFunction=require('myGreatFunction')/typeof=function - 我的模組可以以以下格式使用
import myGreatFunction from 'myGreatFunction'/typeof=function - 我的模組既沒有作為帶有 .default 的物件輸出(當這不被預期時),也沒有作為帶有 .default 的物件輸出(當這確實被預期時)。
感覺上我似乎只能達成其中的一些目標,而無法達成其他目標。
確保這樣做的正確 TSConfig 屬性(上游和下游)咒語是什麼?
最後我妥協了——見下文。
答案#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 客戶端獲取相同的代碼:
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.
