本文介绍了打字稿:如何从javascript文件导入一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想:


  • 导入定义类的js文件: ./ myClass / index .js

  • 在某处(在index.ts或指定的声明文件中)声明 MyClass 的公共方法,我真的不知道怎么做)

  • 有一个暴露类的打字稿文件: index.ts

  • Import a js file that defines a class: ./myClass/index.js
  • Declare the public methods of MyClass somewhere (in index.ts or a specified declaration file, I really don't know how to do it)
  • Have a typescript file that exposes the class: index.ts

类似

// index.ts
import MyClass from './myClass' // or require, or anything that would work
export {MyClass}

// myClass/index.js
export default class MyClass {
  ...
}

这显然不起作用,因为导入 ./ myClass / index 将找不到该模块。

This obviously does not work, as the import of ./myClass/index won't find the module.

事情是,我试图根据,但无论如何,我仍然有一个错误:找不到模块'./myClass/index.js运行时出现错误:(

The thing is, I tried to create a ./myClass/index.d.ts file based on this example, but no matter what, I still have a Error: Cannot find module './myClass/index.js' error at runtime :(

我觉得我在这里错过了一些打字稿基础,但我正在努力寻找一些明确的资源。

I feel like I miss some typescript basics here but I'm striving to find some clear resources.

任何想法?

推荐答案

没有导出默认类JavaScript中的。你能做的就是像这样写你的JS文件。 myClass / index.js

There is no export default class in JavaScript. What you can do is write your JS file like this. myClass/index.js

"use strict";
class MyClass {
  hello(name) {
    console.log(`Hello ${name}`);
  }

}
exports.default = MyClass;

为它创建一个类型定义。 myClass / index.d.ts

Create a Type definitions for it. myClass/index.d.ts

export default class MyClass {
  hello(name: string): void;
}

然后你可以像这样将它导入你的TypeScript。

You can then import it into your TypeScript like this.

/// <reference path="./myClass/index.d.ts" />
import MyClass from "./myClass";

const my = new MyClass();
my.hello("Stack Overflow");

这篇关于打字稿:如何从javascript文件导入一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

阿里云证书,YYDS!

05-22 06:54