Tuesday, May 23, 2017

JavaScript Module Loaders

Typescript supports most of the popular module systems for JavaScript.
These provide a similar functional process of asycronously loading your JS files without the need to create literal SCRIPT tags to bring the files in. The benefits here are listed thoughout posts all over the internet. Some of the benefits that fit a more scientific representation over the opinionations that are widespread:
  • Prevents unneeded files from loading into your applications/webpages
  • Creates a self encapsulating JavaScript loading process that unblocks your application(s) execution
  • Creates more maintainable code.
Using Typescript allows for configuration of any of these systems and all you need to do is attach the appropriate entry point into the JavaScript resources.
Starting out you need to configure your TSCONFIG.JSON file. Modify the compilerOptions node by adding the module property and adding the specific Module Loader you plan to use.

{
 ...,
    "compilerOptions": {
        "module": "amd",
    },
    ...
}


Next you need to bring in the proper Module Loader package via Bower or NPM. It is recommended to use Bower.
bower install --save requirejs

{
  ...,
  "dependencies": {
    "requirejs": "X.X.X"
  }
}



Once you have the package installed you will need to add the appropriate SCRIPT tag to your HTML file to bring it in and initiate the Module Loader.
Note: requirejs leverages the data-main attribute to point to your JavaScript Module files entrypoint. In this example the entrypoint is a file named module.js in the js folder, relative to the file.


Now the remaining work is left to your application files.

js/modules.ts

import * as utilities from './utilities';

// use external function
utilities.doSomething();

// use external class
let beast = new utilities.Animal();

beast.makeSound();

js/utilities.ts

// this function is exported
export function doSomething() {

  console.log('do something');

};

// this class is exported
export class Animal {
  makeSound() {
    console.log('grrrrrr');
  }
}

// this class is not exported
class Secret {
  saySecret() {
    console.log('secret');
  }
}

No comments: