我有一个用TypeScript编写的Express中间件项目。我想在JS&amp ;;中消费它。基于TS的Node项目。
我无法配置项目以确保
myGreatFunction = require('myGreatFunction') // typeof = function
import myGreatFunction from 'myGreatFunction' // typeof = function
感觉好像我只能实现其中一些目标,而不是其他目标。
TSConfig属性(上游和下游)的正确咒语是什么来确保这样?
最后我决定妥协 - 见下文。
答案 0 :(得分: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;
client.ts:
import {MyClass} from "./../src/module";
console.log(MyClass.Version);
编译并运行node client.js
- 参见“1.0”
只需从编译的ts客户端中获取相同的代码:
var module_1 = require("./../src/module");
console.log(module_1.MyClass.Version);
显然相同的输出
答案 1 :(得分:0)
在打字稿中使用打字稿文件。
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.
答案 2 :(得分:0)
最后我决定妥协:
图书馆TSConfig:
Uri geturi = new Uri(URL);
HttpClient client = new HttpClient();
HttpResponseMessage responseGet = await client.GetAsync(geturi);
//string response = await responseGet.Content.ReadAsStringAsync();
//Xml Parsing
List<AClass> obj = new List<AClass>();
XDocument doc = XDocument.Parse(responseGet.Content.ReadAsStringAsync().Result);
foreach (var item in doc.Descendants("row")) //see XML
{
AClass dis = new AClass();
dis.name = item.Element("name").Value.ToString(); //see XML
obj.Add(dis);
}
//Binding listview with server response
picker.ItemsSource = obj;
<强>库:强>
<row>
<id>1</id>
<name>A</name>
</row>
<row>
<id>2</id>
<name>B</name>
</row>
下游项目,TypeScript
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"declaration": true
}
}
下游项目,JavaScript
export = function myGroovyFunction() {...}
TypeScript导入并不像我想的那样简洁,但我可以处理。