Categories
angularjs bower javascript node.js npm

Sharing code between AngularJS and Nodejs

What is the best way of sharing code between frontend and backend using javascript, specifically saying between nodejs and angularjs?

Thing is that we are using same enums and constant values such as error codes in both backend and frontend. Right now we just copy&paste each change to both platform which isn’t a good solution. There are also some services that could be shared.

I have seen libraries such as browserify; but thats not exactly what I am looking for. I am looking for a solution similar to maven dependency in java. In java, libraries can be shared easily using maven, whereas I can’t find a similar way of doing that in javascript.
Is there a way to isolate these services and give them as dependency to nodejs using npm and to angularjs using bower independently? Or what are the ways for sharing the same code between frontend and backend?

There are several ways to do this. The first is that you can make a new package which is required via bower for the front-end code and via npm for the backend code. I have several packages published to both systems.

Install with Bower — information on how to install modules that aren’t in the registry

NPM Install docs — all the ways to install with npm (private github with auth: git+ssh://[email¬†protected]/[org]/[repo])

Just create a new module with your shared data and install it using both package managers. Both of them allow you to install an unpublished module so if it’s private data you can keep it as such.

If your front end requires require.js you can use something like amdefine to make it available to your node backend, or if you’re just using legacy window code you can do something like:

var mydata = {};
if(typeof window !== 'undefined'){
window.mydata = mydata;
} else {
module.exports = mydata;
}

If you are sharing a lot of data though I highly recommend looking into browserify to write your entire codebase in commonjs and using browserify to generate your client bundle. There is a laundry list of resources about using browserify, including stuff on how to use browserify and angular together