Angular2 & TypeScript importing of node_modules

The import rules of TypeScript follow the same convention as node.js. If an import begins with a dot:

import {Something} from './some/path';

Then it is treated as a relative path from the file that declares the import. If however it is an absolute path:

import {Component} from 'angular2/core';

Then it is assumed to be an external module, so Typescript will walk up the tree looking for a package.json file, then go into the node_modules folder, and find a folder with the same name as the import, then looks in the package.json of the module for the main .d.ts or .ts file, and then loads that, or will look for a file that has the same name as the one specified, or an index.d.ts or index.ts file.

Wow that seems complex when written out, and there are still some exceptions there… But all in all, if you have worked with node.js before then this should behave exactly the same way.

One thing to note is that there is a TypeScript compiler option that should be set for typing resolutions to work in this way

in tsconfig.json

"moduleResolution": "node"

Now the second part of your question was how does this get loaded without using ajax calls. This is a feature of System.js. The script tag that is loaded in the index.html file imports a bundle which registers the angular2 bundle with System. Once this has happened System knows about these files and correctly assigns them to their references. It’s a pretty deep topic but a lot of information can be found either in the README of systemjs, or systemjs-builder.

Leave a Comment