如何在clientside上使用node.js模块系统 [英] how to use node.js module system on the clientside
问题描述
我想在客户端javascript应用程序中使用CommonJS模块系统。我选择nodejs作为实现,但是找不到关于如何使用nodejs clientside的任何教程或文档,即不使用节点application.js
I would like to use the CommonJS module system in a clientside javascript application. I chose nodejs as implementation but can't find any tutorial or docs on how to use nodejs clientside, ie without using node application.js
我在html页面中包含了这样的node.js:
I included node.js like this in my html page:
<script type="text/javascript" src="node.js"></script>
请注意,我没有在我的本地机器上制作nodejs,无论如何我都在Windows上(我我知道Cygwin选项。
当我想在我自己的javascript中使用 require
函数时,它表示未定义。
Note that I didn't make nodejs on my local machine, I'm on Windows anyway (I'm aware of the Cygwin option).
When I want to use the require
function in my own javascript it says it's undefined.
var logger = require('./logger');
我的问题是,是否可以使用这样的nodejs?
My question is, is it possible to use nodejs like this?
推荐答案
Node.js
是一个服务器端应用程序,您可以在服务器上运行javascript。你想要做的是在客户端使用 require
函数。
Node.js
is a serverside application where you run javascript on the server. What you want to do is use the require
function on the client.
你最好的选择就是写下自己需要
方法或使用任何其他使用不同语法的实现,例如 requireJS 。
Your best bet is to just write the require
method yourself or use any of the other implementations that use a different syntax like requireJS.
经过一些额外的研究后,似乎没有人使用commonJS语法为客户编写了一个require模块。我最终会在不久的将来写自己的,我建议你这样做。
Having done a bit of extra research it seems that no-one has written a require module using the commonJS syntax for the client. I will end up writing my own in the near future, I recommend you do the same.
一个重要的副作用是 require
函数是同步的,因此加载大块的javascript将完全阻止浏览器。这几乎总是一种不必要的副作用。如果你要这样做,你需要知道你在做什么。设置了requireJS语法,以便可以异步完成。
One important side effect is that the require
function is synchronous and thus loading large blocks of javascript will block the browser completely. This is almost always an unwanted side-effect. You need to know what you're doing if you're going to do this. The requireJS syntax is set up so that it can be done asynchronously.
这篇关于如何在clientside上使用node.js模块系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!