我开始使用电子。
在电子快速启动的index.html中,使用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.");启动电子应用程序后,我在开发工具的控制台中输入日志输出.但是调用flash()不起作用。
当包含脚本时使用
<script src='./renderer.js'></script>我可以打电话给这个函数。
require() 函数从何而来?require**?**包含文件时不能使用函数require() src=""**?**,什么时候使用?发布于 2016-09-02 17:18:13
需方()函数从何而来?
电子中的require和Node.js中的require非常相似。电子不仅仅是一个web浏览器;它的目的是使用HTML、CSS和JavaScript构建桌面应用程序。因为它的目的不仅仅是网络,我认为电子的创建者增加了他们自己的一点触觉,让它成为你可以使用的一项更棒的技术。你可以在这里读到更多关于它的信息:模块。
为什么我不能使用函数时,包括文件使用要求?
这是因为它们是模块中的封闭式,因此它不能用于任何其他脚本文件。
如何使用在所需文件中定义的函数?
为了使用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>何时应该使用src=(),什么时候应该使用“”?
免责声明:我的意见。
喜欢总是使用require。仅当您希望导入不使用script src=''但选择全局声明变量的库时才使用require。
https://stackoverflow.com/questions/39295951
复制相似问题