[英]From Typescript to Javascript
I have a ts code that was translated in js and now i want to use instantiate objects from the generated js code but i am having the error "object" not defined. 我有一个在js中翻译的ts代码,现在我想使用生成的js代码中的实例化对象,但是我没有定义错误“对象”。
For example the class in ts look like this: 例如,ts中的类如下所示:
class Person{
name: string;
constructor(name: string){
this.name = name;
}
/*...*/
}
And the generated js: 和生成的js:
class Person{
constructor(name){
this.name = name;
}
/*...*/
}
now to used the object Person
i did something like this: 现在使用对象
Person
我做了这样的事情:
var bob = new Person("bob");
But i am getting the error: Person is not defined . 但是我得到了错误: 人员未定义 。
class Person { constructor(name) { this.name = name; } } var bob = new Person("bob"); console.log(bob);
So your class declaration and the code that references it are in different files (from your comments). 因此,您的类声明和引用它的代码在不同的文件中(根据您的注释)。
Hence, you should require the class to use it like this: 因此,您应该要求该类像这样使用它:
const Person = require('./Person.js')
And in the file with the class declaration you should export it like this (in the end): 在带有类声明的文件中,您应该这样导出(最后):
module.exports = Person
The above is node module syntax. 以上是节点模块的语法。 Google "browser modules" if you work on browser code.
Google“浏览器模块”(如果您使用浏览器代码)。
But the real question: Why you work on .js
files when you have .ts
ones? 但是真正的问题是:为什么在拥有
.ts
文件时为什么要使用.js
文件? With TS you could use modern modules syntax . 使用TS,您可以使用现代模块语法 。 And it would work in browser or in node, if your TS configured properly.
如果TS配置正确,它将在浏览器或节点中运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.