简体   繁体   中英

Load a single javascript module in both node and the browser

How do I write a single .js file and call (require) it from both node and the browser without making any changes?

An example of where this is useful is Model "classes".

What if the Model has dependencies, such as jquery, which are available on both node and the web?

您可以使用requirejs来允许在浏览器中加载异步模块,并且也可以在节点中使用。

Both the browser and Node can use JavaScript just fine. There is nothing you have to do to run your code in both.

Note however if you use packages available only in Node, or browser objects (such as navigator ), then you will have trouble. You should separate your code into modules that can be easily loaded in both contexts.

In addition, be sure that your code doesn't use newer JavaScript functions, or you will have compatibility problems with older browsers.

This is the module template I use for module to work with both node and require.js:

https://gist.github.com/epoberezkin/5020250

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM