Steviebob Steviebob - 1 month ago 7
Javascript Question

How To Use Typescript Modules

I'm having a bit of difficulty understanding how to correctly create a typescript module.

What I'm trying to achieve is 1 module per file, with no variables leaking into the global scope.

If I have a js file called "shoppingCart.js" for example, with a function within it called "addItem()", I want to only ever be able to access addItem, via "shoppingCart.addItem()".

I can achieve this by creating shoppingCart.js and putting the addItem() function within it, but upon first glance, it appears that the addItem() function is globally scoped.

If I wrap the contents of shoppingCart.js in a module called "shoppingCart", it looks like I get the encapsulation I'm after, however, when I import the module, it's like I have to double name it, e.g.:

import shoppingCart from './shoppingCart'
shoppingCart.shoppingCart.addItem()

I know I could just change the variable on the import statement to something else, but I don't want to, I just want to type in "shoppingCart." and have access to all of it's exported functions classes and variables.

Should I even be using the "module" keyword?
I wanted to use "module" at the root of a module, and only use classes as object containers (And possibly highly related functions where appropriate).

My tsconfig.json has the following properties of interest:

"target": "es5",
"module": "commonjs",
"moduleResolution": "node"


I'm not sure if it makes a difference, but I'm allowing visual studio 2015 to convert the .ts files to .js files, then using browserify with a gulp build process, to concatenate them all into a single file.

Answer

In short.

What I assume you are doing is just exporting the whole file with the global functions. When you should be using a class and creating functions based on what you want to make public for example:

shoppingCart.ts

export class ShoppingCart {
   private _cartNum: number;

   constructor(){
      this._cartNum = 1;
   }

   public class getCartNum(){
       return this._cartnum;
   }
}

The class can now be used as follows:

cartCaller.ts

 import {ShoppingCart} from './shoppingCart';

 const cart: any = new ShoppingCart();
 console.log('You have : ' + cart.getCartNum() +  ' carts');

Hopefully this answers your question.

--Edit: This might help in understanding modules in ts with more detail.

How do I use namespaces with TypeScript external modules?