【问题标题】:Why can't I use functions from javascript-files that are imported by require()?为什么我不能使用 require() 导入的 javascript 文件中的函数?
【发布时间】:2017-01-10 18:42:38
【问题描述】:

我开始使用electron

index.html of electron-quick-start 中包含一个使用require() 的JavaScript 文件。

<script>
  // You can also require other files to run in this process
  require('./renderer.js')
</script>

现在我在renderer.js 中定义了一个名为flash() 的简单函数,以及一个日志输出:

function flash(text) {
  alert("Text: " + text + "!");
}

console.log("Renderer loaded.");

启动电子应用程序后,我在开发工具的控制台中输出日志。但是调用flash() 不起作用。

当使用包含脚本时

<script src='./renderer.js'></script>

我可以调用函数。

  • require()函数从何而来?
  • 为什么我使用require包含文件时无法使用该功能?
  • 如何使用在所需文件中定义的函数?
  • 什么时候应该使用require(),什么时候应该使用src=""

【问题讨论】:

  • @GhanshyamBagul 该帖子并未直接回答有关 Electron 上“require()”的问题。它只是声明“require 是 Node.js/CommonJS 的一部分”。请在发表评论之前仔细阅读问题。

标签: javascript require electron


【解决方案1】:

require()函数从何而来?

Electron 中的 require 与 Node.js 中的 require 非常相似。 Electron 不仅仅是一个网络浏览器;它旨在让您使用 HTML、CSS 和 JavaScript 构建桌面应用程序。因为它的目的不仅仅是网络,我认为 Electron 的创建者添加了他们自己的一点点触感,使其成为一种更棒的技术,你可以使用。你可以在这里阅读更多信息:https://nodejs.org/api/modules.html#modules_modules

为什么我使用require包含文件时不能使用该函数?

这是因为它们在模块内是enclosed,因此它对任何其他脚本文件都不可用。

如何使用在所需文件中定义的函数?

要使用flash 函数,您需要将其导出,如下所示:

function flash(text) {
  alert("Text: " + text + "!");
}
module.exports.flash = flash;
// Note: this is how we export. We assign properties to the `module.exports`
//   property, or reassign `module.exports` it to something totally
//   different. In  the end of the day, calls to `require` returns exactly
//   what `module.exports` is set to.

console.log("Renderer loaded.");

但仅此一项并不能让您轻松使用flash 函数;你不得不 像这样从require 调用中明确获取它:

<script>
  // You can also require other files to run in this process
  var renderer = require('./renderer.js');

  renderer.flash('Some text');
</script>

什么时候应该使用 require() 什么时候应该使用 src=""?

免责声明:我的意见。

总是喜欢使用require。仅当您要导入不使用 require 而是选择全局声明变量的库时才使用 script src=''

【讨论】:

    猜你喜欢
    • 2018-05-19
    • 2021-05-07
    • 1970-01-01
    • 2015-05-17
    • 2022-01-15
    • 1970-01-01
    • 2020-12-23
    • 2013-10-01
    • 2018-09-24
    相关资源
    最近更新 更多