How to include javascript for both main process an

2019-07-18 16:14发布

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条回答
【Aperson】
2楼-- · 2019-07-18 16:42

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.

查看更多
登录 后发表回答