Node.js and client sharing the same scripts

后端 未结 1 507
广开言路
广开言路 2021-01-11 14:21

One of the theoretical benefits from working with Node.js is the possibility to share the same scripts between clients and the server. That would make it possible to degrade

相关标签:
1条回答
  • 2021-01-11 15:01

    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.

    Solutions are:

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

    2. Do your own loader

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

    0 讨论(0)
提交回复
热议问题