如果我有一个仅打印到屏幕上的简单 typescript 类,如下所示,如何以更简单的方式在前端访问它?
语音.ts
export class Speak {
public write() {
console.log("Hello");
}
}
我知道你能用
index.html
<script>
var x = require('./speak');
x.Speak.prototype.write(); // Prints "Hello"
</script>
require
语句必须分配一个变量,以便我访问此类。我无法单独使用require('./speak');
来访问它,试图将其带入全局范围。必须为每个命令加上“x.Speak.prototype”有点冗长,并且在引入多个类和接口(interface)时很容易变得更长。
我觉得我做的方法不正确。如何从TypeScript类获取数据/函数以在前端进行操作?
更新
当我在
index.html
文件中尝试以下内容时<script>
var speak = new Speak();
speak.write("some other stuff");
</script>
我收到一个错误:
Uncaught ReferenceError: Speak is not defined
最佳答案
涉及两件事。
首先,您要声明一个ES6模块,同时以commonJs语法使用它。
这就是为什么您需要额外的
X
来保留CJS中的模块对象的原因:var X = require('./speak');
var speak = new X.Speak();
// or accessing the `Speak` class directly:
var Speak = require('./speak').Speak;
var speak = new Speak();
如果您在ES6中使用相同的代码,则可能是:
import { Speak } from './speak'
const s = new Speak();
// or
import * as X from './speak'
const s = new X.Speak();
当然,并不是每个浏览器都提供ESM(ES6模块系统),因此您需要将TypeScript代码转换为ES5,并使用某种加载器机制加载模块(例如requireJS)。
第二点,您正在编写一个类。因此,您通常会创建一个
Speak
实例并使用它(以下代码假定您在模块中使用了该代码,以避免与第一点混淆):var speak = new Speak();
speak.write();
如果不需要实例,则可以使用静态方法或仅使用函数:
export class Speak {
static write() { ... }
}
// usage:
Speak.write();
// function
export function write() { ... }
// usage:
write();
关于javascript - 将TypeScript对象传递给Electron应用程序中的Window,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44011961/