Skip to content

Modules

splitting code into multiple files

  1. namespaces and file bundling
  2. ES6 modules

namespaces

  • namespaces are a way to organize code in a way that makes it easy to find the code you need
  • namespaces are a typescript feature.
  • namespaces get compiled to normal object in javascript.
  • you don’t need to export the namespaces, but you have to export the members of the namespace.
  • you have to use special syntax to import and access the namespaces.
  • you can put any code/types/classes/functions in a namespace.
// namespaces.ts
namespace MyNamespace {
    export class MyClass {
        // ...
    }

    // any code can go here, functions, types, classes, etc.
}
  • import name space
/// <reference path="./path-to-name-space/namespace.ts"/>
  • it is possible to span namespaces in multiple files.
// namespaces.ts
namespace App {
    export const myVariable = "hello";
}

// app.ts
/// <reference path="./path-to-name-space/namespace.ts"/>

namespace App {
    console.log(myVariable); // my variable is available in the app.ts file
}
  • exported members from any namespace file, can be accessed in any other file in the same namespace.
  • js config necessary to use the namespaces.
{
    "compilerOptions": {
        "module": "amd",
        "outFile": "./dist/bundle.js"
    }
}

ES6 modules

  • every file that has import/export statements, is a module, modules have module scope.
  • files with no import/export statements, are not scripts, scripts are available in the global scope.
  • when importing something from a module, the module loader will look into the imported module, grab the variable, and define it in the importing module scope.
  • popular module loaders are: amd, system, commonjs, umd.
  • js config necessary to use the ES6 modules:
{
    "compilerOptions": {
        "module": "es2015"
    }
}
  • namespaces and ES6 modules are not compatible.
  • bundlers like webpack, rollup, etc. can bundle namespaces and ES6 modules.
  • bundlers can also bundle multiple files into a single file.
  • bundlers convert modules to bundles (non-model, single file) so that modules can work in older browsers.
  • if models are bundled, the browser needs to make a request to get every single imported file (in browser environments).