How to include javascript for both main process and renderer

。_饼干妹妹 提交于 2019-12-12 18:21:31

问题


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.

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.

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)


回答1:


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

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.

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> 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.



来源:https://stackoverflow.com/questions/34981122/how-to-include-javascript-for-both-main-process-and-renderer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!