简体   繁体   English

电子和打字稿:如何在运行时正确处理模块?

[英]Electron and Typescript: How do I handle modules at runtime correctly?

I'm writing an Electron desktop application in Typescript. 我正在用Typescript编写Electron桌面应用程序。 After compilation, the project organization looks something like this: 编译后,项目组织如下所示:

  • dist DIST
    • html HTML
      • index.html 的index.html
    • scripts 脚本
      • ApplicationView.js ApplicationView.js
      • ApplicationViewModel.js ApplicationViewModel.js

In index.html I have this script tag: index.html我具有以下脚本标记:

<script src="../scripts/Application.js"></script>

All my files are compiled from Typescript to ES2015 (targeting ES6 and using ES6 modules) and transpiled by Babel to ES5. 我所有的文件都从Typescript编译到ES2015(以ES6为目标并使用ES6模块),并由Babel编译为ES5。 ApplicationView.ts looks like this: ApplicationView.ts看起来像这样:

///<reference path="../../typings/main.d.ts" />

import * as $ from "jquery";
import * as ko from "knockout";
import ApplicationViewModel from "./ApplicationViewModel";

$(document).ready(() => {
    ko.applyBindings(new ApplicationViewModel("Hello!"));
});

Here's the contents of ApplicationViewModel.ts : 这是ApplicationViewModel.ts的内容:

import * as ko from "knockout";

export default class ApplicationViewModel {
    public greeting: KnockoutObservable<string>;

    constructor(greeting: string) {
        this.greeting = ko.observable(greeting);
    }
}

Electron throws an error saying it can't find the module ./ApplicationViewModel . Electron抛出错误,提示它找不到模块./ApplicationViewModel However, in the debugger console, I can successfully import the module with: 但是,在调试器控制台中,我可以使用以下命令成功导入模块:

require("../scripts/ApplicationViewModel");

So, what's wrong is obvious. 所以,明显的问题是。 The script tag effectively copies the contents of Application.js into the HTML file, changing the context for the module's relative path. 脚本标记可将Application.js的内容有效地复制到HTML文件中,从而更改模块相对路径的上下文。 My question is what should I really be doing? 我的问题是我该怎么办?

I've seen the use of require.js in the script tag. 我已经在script标记中看到了require.js But Electron runs on Node.js. 但是Electron在Node.js上运行。 If this is the right way to handle my problem, why then would I need another module loader? 如果这是解决我的问题的正确方法,那么为什么我需要另一个模块加载器? How would I make sure the two play nice? 我要如何确保两者的表现融洽?

Figured it out. 弄清楚了。 Pretty simple actually. 其实很简单。 I replaced the <script> tag in the HTML file with this: 我用以下代码替换了HTML文件中的<script>标记:

<script>
    require("../scripts/ApplicationView");
</script>

Works like a charm! 奇迹般有效! Now I just need to figure out why JQuery isn't working properly... 现在我只需要弄清楚为什么JQuery无法正常工作...

You are mixing up the es5 and the es6 ways to export modules: 您正在混淆es5和es6导出模块的方式:

module.exports =  ApplicationViewModel; // ES5
export default ApplicationViewModel; // ES6

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

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