本文介绍了如何在浏览器中“要求” CommonJS模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

在浏览器中将CommonJS模块作为客户端JavaScript代码加载的最佳方法是什么?


模块将其功能放在 module.exports 命名空间中,通常使用 require来包含(服务器端脚本中的pathToModule)。在客户端上加载它们的工作方式不同(需要替换需求,需要考虑异步性等)。


我发现了模块加载器和其他解决方案:Browserify ,RequireJS,yabble等,或简单地更改模块的方法。您认为最好的方法是什么?为什么?

解决方案

我用过在过去已经广泛使用(2010年在上实现),并且效果很好。它可以处理CommonJS模块,但是需要一个额外的包装器,我觉得很烦。
如果还要在node.js中使用这些模块,则还需要在服务器端使用requirejs,我不喜欢这样做,因为它不是惯用的node.js JavaScript。



我使用了和在过去的几个项目中。最初,编译步骤使我望而却步,但是今年已经广泛使用它,我可以说这不是问题。



Browserify具有监视功能,其中包括效果很好。 Webmake可以连接到观察者(例如),或者,您可以使用模块,可用作快速或连接应用程序的一部分。这样的好处是,仅在您实际请求时才编译JavaScript,而不是在每次保存时都编译JavaScript。
使创建服务器(也是静态的)变得很简单,因此您可以创建一个很小的静态node.js。



奖金:不需要构建脚本,因为您始终可以处理构建的代码。


What is the best way to load CommonJS modules as client-side JavaScript code in the browser?

CommonJS modules put their functionality in the module.exports namespace and are usually included using require(pathToModule) in a server-side script. Loading them on the client cannot work the same way (require needs to be replaced, asynchronousness needs to be taken into account, etc.).

I have found module loaders and other solutions: Browserify, RequireJS, yabble, etc. or ways to simply alter the modules. What do you consider the best way and why?

解决方案

I have used requirejs extensively in the past (implementation on BBC iPlayer in 2010) and it works well. It can handle CommonJS modules, but it needs an additional wrapper, which I find annoying.If you want to use those modules in node.js as well, you need to use requirejs on the server side as well, which I don't like doing since it is not idiomatic node.js JavaScript.

I have used webmake and browserify in the past year on a few projects. Initially, the compilation step put me off, but having used it extensively this year, I can say that this is not an issue.

Browserify has a watch function included, which works very well. Webmake can be hooked up to a watcher (such as watchr) or, you can use the webmake-middleware module, which can be used as part of an express or connect app. This has the advantage that rather than compiling the JavaScript on each save, it is only compiled when you actually request it.Connect makes it trivial to create a server (also static), so you could create a tiny static node.js server to serve up your files if you want to develop your frontend without a backend.

Bonus: no need for a build script as you always deal with the built code.

这篇关于如何在浏览器中“要求” CommonJS模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 12:56