如何在主过程和渲染器中都包含javascript [英] How to include javascript for both main process and renderer

查看:42
本文介绍了如何在主过程和渲染器中都包含javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个电子项目中,我发现,如果我将带有module.exports的javascript放在node_modules文件夹中,则可以在任意位置通过require()从主进程和渲染器进程访问它.

In an electron project, I've found that if I put javascript with module.exports in the node_modules folder I can access it from both the main process and renderer process by require() from either place.

这是访问常见javascript的正确方法,还是有不同的最佳实践?

Is this the correct method of accessing common javascript, or is there a different best-practice?

假设没有特殊的原因需要它是节点模块,例如全局配置对象.

Assume there's no particular reason it needs to be a node module- like say a global configuration object.

类似地-除了稍微凌乱的文件夹结构之外,此方法与渲染器过程中通过< script> 标记链接到此方法相比,是否有任何实际的改进?(在这种情况下,假设所有内容都放在一个文件夹中,只是为了保持简单)

Similarly- aside from a slightly messier folder structure, are there any practical ramifications to this method vs. linking to it via <script> tags in the renderer process? (in this case assuming everything in one folder, just to keep it simple)

推荐答案

这是访问常见javascript的正确方法,还是有不同的最佳实践?

Is this the correct method of accessing common javascript, or is there a different best-practice?

这确实是您应该加载 Node模块的方式,但是您的某些脚本文件(或第三方库)可能未编写为模块.启用节点集成后,您可以使用 require node_modules ,源目录或应用程序ASAR加载模块.

This is indeed how you should be loading Node modules, but some of your script files (or third-party libs) may not be written as modules. When Node integration is enabled you can load modules from node_modules, your source directory, or the app ASAR using require.

类似地-除了稍微凌乱的文件夹结构之外,此方法与渲染器过程中通过< script> 标记链接到该方法相比,是否有任何实际的改进?

Similarly- aside from a slightly messier folder structure, are there any practical ramifications to this method vs. linking to it via <script> tags in the renderer process?

< script> 标记将所有内容推送到全局名称空间,这在某些情况下很有用,并且某些浏览器库(如jQuery)希望以这种方式加载.您不应该通过< script src ="path/to/module.js"> 加载Node模块,尽管在< script> 标记.

<script> tags shove everything into the global namespace, this can be useful in some cases, and some browser libs (like jQuery) expect to be loaded that way. You shouldn't be loading Node modules via <script src="path/to/module.js">, though it's perfectly reasonable to call require within a <script> tag.

这篇关于如何在主过程和渲染器中都包含javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆