Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern for sharing a library between angularjs and node.js

How can I share a library between angularjs and node.js?

For example an angularjs service is often a reusable piece of code. Let's take a URL library as an example (pick apart and construct URLs).

The same library should be usable in node.js.

My constraint is that I want to share the library code, but I do not want to restrict myself to any loader library on the browser side. So if I need to use RequireJS in the browser, I need to disable any loading part so that can be controlled elsewhere.

So how do I share code?

like image 756
user239558 Avatar asked Nov 30 '13 03:11

user239558


1 Answers

What you'll see in a lot of different places that support multiple environments is wrapping the entire returned value from your 'service' into a parameter passed to an initialization function from a closure. The one catch to keep in mind with angular is that service probably shouldn't have other dependencies to remain environment agnostic (If this was a simple utility file for example, there would not likely be conflict).

As an example consider:

(function( myService){

  if (typeof module !== 'undefined' && module.exports ) {
    module.exports = myService;
  } else if( angular ){
    angular.module('yourModule', [])
    .factory('serviceNameHere', function(){ return myService; });
  } else {
    window.myService = myService;
  }

}(function(){
  function foo(){/* Do something */}
  function bar(){/* Do something else */}

  return {
    foo: foo,
    bar: bar
  }
}()))

You could still have dependencies if desired via nodes require syntax, or angular's dependency injection, but the service would likely need modification as it moved from one project to another.

like image 97
Ryan Q Avatar answered Oct 13 '22 21:10

Ryan Q