Alain
Alain

Reputation: 1470

How to share a class development between node module and browser environment

I have this code developped for node.js:

user.js:

var Underscore = require( '/usr/local/lib/node_modules/underscore' ),
    Backbone = require( '/usr/local/lib/node_modules/backbone' );

var User = Backbone.Model.extend( {

   // Handle calls to Mysql 

});
module.exports = User;

And I have this code developped for the browser:

user.js:

define( function( require ) {
    var Backbone = require( "backbone" );
    var User = Backbone.Model.extend( {

    } );

    return lUser;
} );

Is it possible to share one file of User implementation for both environment ?

Upvotes: 0

Views: 59

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146064

Yes, you can do this. It's a bit of a tricky problem and there are several different attempts to solve it. My current recommendation is this approach:

  • code everything exclusively as node.js-style CommonJS modules
    • this means use require and module.exports but not define, no wrapper functions, etc
  • use browserify to package up a bundle of code and ship it to the browser
  • use packages from npm whenever they are available (backbone, underscore, etc), otherwise use browserify's support for non-npm libraries to shim things as needed (angularjs, etc)

Use the available tutorials online. It will take some effort to get the hang of things, but once you're over the learning curve, you'll be able to share and reuse code pretty effectively.

Note about your code snippet above: require modules by name when they are available in npm, or relative path when needed, but never use an absolute path like you have above.

Upvotes: 1

Related Questions