如何在浏览器中要求CommonJS模块? [英] How to require CommonJS modules in the browser?

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

问题描述

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

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

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

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

我找到了模块加载器和其他解决方案:Browserify,RequireJS,yabble等,或者简单地改变模块的方法。您认为最好的方式和原因是什么?

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?

推荐答案

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

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.

我使用了 webmake 在过去的一年中对一些项目进行了浏览。最初,编译步骤让我失望,但今年广泛使用它,我可以说这不是问题。

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包含一个监视功能,效果很好。 Webmake可以连接到观察者(例如监视器),或者,您可以使用webmake-middleware 模块,可用作快速或连接应用程序的一部分。这样做的好处是,不是在每次保存时编译JavaScript,而是仅在实际请求时编译它。
Connect 使得创建服务器(也是静态的)变得微不足道,因此您可以创建一个微小的静态node.js如果你想在没有后端的情况下开发你的前端,服务器就会提供你的文件。

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模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆