typescript 打字稿:如何从 javascript 文件中导入一个类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40463441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript: how to import a class from a javascript file?
提问by aherve
I would like to :
我想 :
- 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
- 导入定义类的js文件:
./myClass/index.js
- 声明
MyClass
某处的公共方法(在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 ?
有任何想法吗 ?
回答by goenning
There is no export default class
in JavaScript. What you can do is write your JS file like this. myClass/index.js
export default class
JavaScript 中没有。你可以做的是像这样编写你的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
为它创建一个类型定义。 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");
回答by siva
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