且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Node.js和客户端共享相同的脚本

更新时间:2022-06-21 22:14:06

总之,如果你想重复使用脚本, t使用Node.js特定的东西,你必须用最低的共同点在这里,浏览器。

In short, if you want to re-use scripts don't use Node.js specific stuff you have to go with the lowest common denominator here, the Browser.

解决方案是:


  1. 过度使用并使用 RequireJS ,此将使它工作在Node.js和浏览器。但你需要在服务器端使用RequireJS格式,并且还需要插入一个即时转换脚本...

  1. Go overkill and use RequireJS, this will make it work in both Node.js and the Browser. But you need to use the RequireJS format on the server side and you also need to plug in an on the fly converted script...

自己的加载器


  1. 使用匿名函数将重复使用的脚本包含在服务器端和客户端

  2. 现在创建一些代码,用户调用(模块)在该函数上,在节点侧传递 this 模块,在客户端传递一个命名空间对象

  1. Wrap your re-use scripts both on the server and client side with an anonymous function
  2. Now create some code that users call(module) on that function, on the Node side you pass in this for the module, on the client side you pass in a name space object


  • 保持简单和愚蠢,并且不要在Node.js端的模块作用域中使用

  • Keep it simple and stupid, as it is now, and don't use this in the module scope on the Node.js side of things

    我希望我能给你一个简单的开箱即用的解决方案,但两种环境在这种情况下有很大不同。如果你真的有大量的代码,你可以考虑一个生成脚本生成文件。

    I wish I could give you a simple out of the box solution, but both environments differ to much in this case. If you really have huge amounts of code, you might consider a build script which generates the files.