简体   繁体   English

在节点和浏览器中加载单个javascript模块

[英]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? 如何编写单个.js文件并从节点和浏览器调用(require)它而不进行任何更改?

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? 如果模型具有可在节点和Web上使用的依赖项(例如jquery),该怎么办?

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

Both the browser and Node can use JavaScript just fine. 浏览器和Node都可以使用JavaScript。 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. 但是请注意,如果您使用仅在Node或浏览器对象(例如navigator )中可用的包,那么您将遇到问题。 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. 此外,请确保您的代码不使用较新的JavaScript函数,否则您将遇到旧版浏览器的兼容性问题。

This is the module template I use for module to work with both node and require.js: 这是我用于模块以使用node和require.js的模块模板:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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