【问题标题】:Electron -- requiring module in Chromium scriptElectron——在 Chromium 脚本中需要模块
【发布时间】:2017-04-30 10:59:36
【问题描述】:

我正在尝试使用 Electron 应用程序,并且在尝试从 Chromium 浏览器窗口中运行的另一个脚本中要求模块时遇到问题。无论我如何指定相对路径,我总是遇到关于无法找到模块的相同错误。

我的项目是这样设置的:

    index.html
    scripts
        controllers
            controller.js
        models
            game.js
        tests
            spec
                gameSpec.js

我的 index.html 是 electron 启动时默认打开的页面,将 controller.js 作为普通脚本加载到 body 标签的末尾。

<script src="scripts/controllers/controller.js"></script>

controller.js 顶部有以下代码:

var Game = require("../models/game.js");
.... some other code .....
var game = new Game();

在启动电子 Chromium 窗口时,我立即遇到了这个问题:

Uncaught Error: Cannot find module '../models/game.js'

我的假设是我需要一个从 controller.js 文件到它正在导入的 game.js 文件的相对路径,但无论我进行何种调整,我总是会遇到该错误。我不认为这仅仅是一个语法错误,因为我在测试文件夹下的规范都在运行并通过,它成功地使用了这样的要求:

var Game = require("../../models/game.js");
describe("Game", function () { ... });

我是否对从 Chromium 浏览器执行时需要相对路径的方式做出了错误的假设?任何帮助表示赞赏!

【问题讨论】:

    标签: javascript node.js module electron requires


    【解决方案1】:

    也许更多的是一种解决方法而不是答案,但如果你从这里交换你的脚本包含:

    <script src="scripts/controllers/controller.js"></script>
    

    到这里:

    <script>require('./scripts/controllers/controller.js')</script>
    

    那么相对路径应该可以正常工作。


    认为当您包含具有src 属性的脚本时,该文件中当前工作目录的内部上下文就是应用程序的根目录。

    为什么?老实说,我不是 100% 确定。当包含为脚本src 时,文件必须如何加载的限制?如果您真的想继续使用src 属性,这些在技术上可以在controller.js 中使用。

    var Game = require(__dirname + '/scripts/models/game.js');
    // or
    var Game = require('./scripts/models/game.js');
    

    不过,我不能全心全意地建议其中任何一个选项。看起来很脆弱。

    说实话,我以前从未注意到这一点,因为我通常会在我的index.html 所在的位置包含一个指向我的应用程序的 javascript“入口”点。

    【讨论】:

    • 感谢您的回复!不幸的是 没有工作,导致同样的错误。幸运的是,您对 var Game = require(__dirname....) 的建议就像一个魅力,尽管我同意它看起来很脆弱,让我担心当我想打包应用程序时会发生什么。我正在将这个项目从没有 Node 的 .Net 转换过来,所以我正在尝试在迁移中采取一些小步骤。
    • 这里的问题是controller.js是一个CommonJS/Node模块,但是&lt;script src="path/to/controller.js"&gt;&lt;/script&gt;对CommonJS模块一无所知,它只会将文件的内容加载到当前文档中而不经过Node的模块加载器。正如@dvlsg 指出的那样,加载controller.js 的正确方法是使用require
    猜你喜欢
    • 2018-08-26
    • 2019-03-24
    • 2023-03-08
    • 2019-12-31
    • 2017-07-22
    • 2022-10-16
    • 2017-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多