我已经在节点api中创建了一个ts文件并将其导出。
下面是myClass.ts文件的代码
class myClass{
firstFunction(firstParam, secondParam) {
return firstParam + secondParam
};
}
module.exports.myClass = myClass;
有一个js文件是index.js
下面是代码
const myClass= require('./myClass.ts');
myFunction(){
myClass.firstFunction("firstValue", "secondValue");
}
但是以上代码使我收到了以下异常。
**UnhandledPromiseRejectionWarning: TypeError: myClass.firstFunction is not a function**
at "myMachinePath\index.js:368:20"
at processTicksAndRejections (internal/process/task_queues.js:94:5)
warning.js:27
(node:14944) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async
function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
是否可以使用require在js中使用ts文件?
我已经尝试安装
npm install --save-dev babel-cli babel-preset-es2015
但是我仍然得到同样的例外。我无法将js文件更改为ts。
要么使您的方法变为静态
class myClass{
static firstFunction(firstParam, secondParam) {
return firstParam + secondParam
};
}
module.exports.myClass = myClass;
或创建类的实例,然后调用函数
const MyClass= require('./myClass.ts');
myFunction(){
const myClass = new MyClass();
myClass.firstFunction("firstValue", "secondValue");
}