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

时间:2016-09-02 15:27:16

标签: javascript require electron

我开始使用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>

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

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

console.log("Renderer loaded.");

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

使用

包含脚本时
<script src='./renderer.js'></script>

我可以调用该函数。

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

1 个答案:

答案 0 :(得分:7)

  

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。如果要导入不使用script src=''的库,而是选择全局声明变量,则仅使用require