Node.js re-usable code server-client
-
29-10-2019 - |
Pergunta
I'm doing some R&D on Node.js and so far I like it, I'm just curious on how I could re-use code in order to have some shared code between client and server.
A good example of that need would be Backbone.js which I installed with npm.
Currently I have a directory that looks like this:
app.js
public/
routes/
views/
node_modules/
tests/
Obviously I use express.js and all my client-side code is under public
folder where css
, images
, js
files are located.
So how I could have a model in backbone which I could use it in both server and back?
Also I used to use JavaScript AMD with Require.js in order to structure and modulize my application, I got used to it and I tend to like it I saw require.js is available via npm but now that I installed it I'm not sure how I cal use it in client-side since I used to have something like this: <script data-main="js/main" src="js/libs/Require/require.js">
but since require.js is installed via npm it is isn't under public folder so I can't see any possible way to load it.
Thanks
Solução
You could add a symbolic link (ln -s) to require.js from the public folder.
I think you can just place the backbone model in public as well and then use requirejs both on the server and the client to load the same file.
Outras dicas
I guess this is somewhat late, but I just wanted to add that instead of using browserify on the client side, you can use https://npmjs.org/package/define on the server side, which lets you define modules in AMD-style, but require them with node's require()