简体   繁体   English

打字稿:如何从javascript文件导入一个类?

[英]Typescript: how to import a class from a javascript file?

I would like to : 我想要 :

  • Import a js file that defines a class: ./myClass/index.js 导入定义类的js文件: ./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) 在某处声明MyClass的公共方法(在index.ts或指定的声明文件中,我真的不知道该怎么做)
  • Have a typescript file that exposes the class: index.ts 有一个暴露类的index.ts文件: index.ts

something like 就像是

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

and

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

This obviously does not work, as the import of ./myClass/index won't find the module. 这显然不起作用,因为./myClass/index的导入将找不到该模块。

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 :( 问题是,我试图基于这个例子创建一个./myClass/index.d.ts文件,但无论如何,我仍然有一个错误:在运行时找不到模块'./myClass/index.js'错误:(

I feel like I miss some typescript basics here but I'm striving to find some clear resources. 我觉得我在这里错过了一些打字稿基础,但我正在努力寻找一些明确的资源。

Any ideas ? 有任何想法吗 ?

There is no export default class in JavaScript. JavaScript中没有export default class What you can do is write your JS file like this. 你能做的就是像这样写你的JS文件。 myClass/index.js

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

}
exports.default = MyClass;

Create a Type definitions for it. 为它创建一个类型定义。 myClass/index.d.ts

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

You can then import it into your TypeScript like this. 然后,您可以像这样将它导入TypeScript。

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

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

at the end of the your javascript file , write this 在你的javascript文件的末尾,写下这个

exports.MyClass = MyClass;

in ts files 在ts文件中

import * as  IzendaSynergy  from './izenda/izenda_ui.js';

or 要么

import { IzendaSynergy } from './izenda/izenda_ui.js';

in tsconfig.json file 在tsconfig.json文件中

  "allowJs": true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM