[英]Pass TypeScript object to Window in Electron app
If I have a simple typescript class that just prints to the screen, like below, how can I access it on the front end in a simpler way? 如果我有一个仅打印到屏幕上的简单打字稿类,如下所示,我如何以更简单的方式在前端访问它?
speak.ts 说话
export class Speak {
public write() {
console.log("Hello");
}
}
I know you are able to use 我知道你能用
index.html index.html
<script>
var x = require('./speak');
x.Speak.prototype.write(); // Prints "Hello"
</script>
The require
statement has to assign to a variable for me to access this class. require
语句必须为我分配一个变量才能访问此类。 I'm not able to access it using require('./speak');
我无法使用
require('./speak');
访问它require('./speak');
on its own, trying to bring it into global scope. 试图将其纳入全球范围。
Having to preface every command with "x.Speak.prototype" is a bit verbose, and could easily become much longer when multiple classes and interfaces are introduced. 必须为每个命令加上“ x.Speak.prototype”有点冗长,并且在引入多个类和接口时很容易变得更长。
I feel like I'm not doing this the right way. 我觉得我做的方法不正确。 How can I bring data/functions over from TypeScript classes to operate on the front end?
如何从TypeScript类获取数据/函数以在前端进行操作?
UPDATE 更新
When I try something like below in my index.html
file 当我在
index.html
文件中尝试以下内容时
<script>
var speak = new Speak();
speak.write("some other stuff");
</script>
I get an error: Uncaught ReferenceError: Speak is not defined
我收到一个错误:
Uncaught ReferenceError: Speak is not defined
There are two things involved. 涉及两件事。
For the first point, you are declaring an ES6 module while consuming it in commonJs syntax. 首先,您要声明一个ES6模块,同时以commonJs语法使用它。
that's why you need the extra X
to hold on to the module object in CJS: 这就是为什么您需要额外的
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();
If you consume the same code in ES6, it would be: 如果您在ES6中使用相同的代码,则可能是:
import { Speak } from './speak'
const s = new Speak();
// or
import * as X from './speak'
const s = new X.Speak();
Of course, ESM (ES6 Module system) is not available in every browser, so you need to transpile your TypeScript code down to ES5 and use some loader mechanism to load the module (like requireJS). 当然,并不是每个浏览器都提供ESM(ES6模块系统),因此您需要将TypeScript代码转换为ES5,并使用某种加载器机制加载模块(例如requireJS)。
For the second point, you are writing a class. 第二点,您正在编写一个类。 so you typically would create an instance of
Speak
and use it (following code assume you consume the code in a module, to avoid confusion with the first point): 因此,您通常会创建一个
Speak
实例并使用它(以下代码假定您在模块中使用了该代码,以避免与第一点混淆):
var speak = new Speak();
speak.write();
If you don't need an instance, you can use a static method or just function: 如果不需要实例,则可以使用静态方法或仅使用函数:
export class Speak {
static write() { ... }
}
// usage:
Speak.write();
// function
export function write() { ... }
// usage:
write();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.