javascripttypescriptbundlejavascript-namespaces

Bundle javascript library with namespace and classes in different files


I have different files with namespace and classes like this:

1) namespace.js:

var somenamespace = window.somenamespace || {};

2) class1.js:

somenamespace.class1= (function() {
  var _public = {};
  _public.someBoolean= false;
  return _public;
})();

3) class2.js:

somenamespace.class2= (function() {
  var _public = {};
  _public.init= function() {
  };
  return _public;
})();

I need to bundle them and expose them on a library. Something like this:

expose default {
  somenamespace
};

in order to use it in another project. Something like this:

import * as somenamespace from 'somenamespace';

var a = function() {
    somenamespace.class1.someBoolean = true;
    ansomenamespace.class2.init();
};

How can I do it? (I would like also expose its types definition for typescript use) Thanks!


Solution

  • You are mixing the import / export style modules and the type that are attached to window. I would recommend picking one or the other.


    For example to attach everything to window:

    namespace.js

    var somenamespace = window.somenamespace || {}; // not strictly necessary
    

    class1.js

    var somenamespace = window.somenamespace || {};
    
    somenamespace.class1= (function() {
      var _public = {};
      _public.someBoolean= false;
      return _public;
    })();
    

    class2.js

    var somenamespace = window.somenamespace || {};
    
    somenamespace.class2= (function() {
      var _public = {};
      _public.init= function() {
      };
      return _public;
    })();
    

    using the module

    // no import, just read it off of window
    
    var a = function() {
        window.somenamespace.class1.someBoolean = true;
        window.ansomenamespace.class2.init();
    };
    

    Alternatively, I'd recommend import / export, though you need to be transpiling your code with Babel or Webpack or something similar, since not all browsers support ES modules:

    namespace.js

    export {class1} from './class1'
    export {class2} from './class2'
    

    class1.js

    export const class1 = (function() {
      var _public = {};
      _public.someBoolean= false;
      return _public;
    })();
    

    class2.js

    export const class2 = (function() {
      var _public = {};
      _public.init= function() {
      };
      return _public;
    })();
    

    using the module

    import * as somenamespace from './namespace'
    
    var a = function() {
        somenamespace.class1.someBoolean = true;
        ansomenamespace.class2.init();
    };