为什么我不能使用通过require()导入的javascript文件中的函数?

8
我开始使用electron
electron-quick-start的index.html中,使用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=""

请参考此帖子:https://dev59.com/4mkw5IYBdhLWcg3wbp8S - Ghanshyam Bagul
@GhanshyamBagul那篇帖子并没有直接回答有关Electron中“require()”的问题。它只是说明“require是Node.js/CommonJS的一部分”。请在留言之前仔细阅读问题。 - Sal Rahman
1个回答

10

require()函数是从哪来的?

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

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

这是因为它们被封装在模块内部,因此其他脚本文件无法使用它。

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

为了使用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=''


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接