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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With