Use modular define pattern in react-native

136 Views Asked by At

I have some web app modules (which i treat as object classes), I would like to reuse them in react-native.

However define doesn't work. I tried amdefine but got nowhere with that. The error I get is "define is undefined". Any ideas?

An example:

THE CALLER (index.ios.js):

var React = require('react-native');
var ExampleClass = require('./app/ExampleClass');
....

THE DEFINITION:

define('ExampleClass', [
    // imports
    'ParentClass',
    'ExampleImport',
    'ExampleImport2',
], function(ParentClass, ExampleImport, ExampleImport2) {

    /**
     * @class ExampleClass
     */
    var ExampleClass = ParentClass.extend('ExampleClass');

    ExampleClass.prototype.init = function() {
        ParentClass.prototype.init.call(this);
        var oExampleImport = new ExampleImport();
        oExampleImport.doStuff();
    };


    ExampleClass.prototype.doSomething = function(oData, oStatus) {
       .....
       var oExampleImport2 = new ExampleImport2();
       oExampleImport2.doMoreStuff();
    };

    return ExampleClass;
});
1

There are 1 best solutions below

0
On

So after a little investigation, I have came up with a solution (which I still need to put in place: :p):

  • Isolate the shared modules as generic node modules

    'use scrict';
    
    let Module2 = require('../app/modules/Module2');
    
    let Module = {};
    
    Module.prototype.init = function() {
       let m2 = new Module2();
       m2.doSomething();
    };
    
    module.exports = Module;
    

    I could make this more ES6 of course with a class structure etc.

  • Use something like browserify or webpack to package the project:

    This would allow the web app to be able to use the shared modules (e.g. so it understands such code as module.exports and ES6 syntax).

    It would also behave like one big package.

  • Only the views will be specific to the target platform (iOS, web browser):

    Each view class would just require the necessary sub-class.

Comments welcome. :)