yaquawa
yaquawa

Reputation: 7338

What exactly happens when ` import Foo from "Bar" ` in TypeScript

When you import a module without a '.' or '..'
For example : import File from 'FileClass';
How the ts compiler resolves 'FileClass' exactly?

The Doc says

  • Module names may be relative or top-level. A module name is relative if the first term is "." or "..".
  • Top-level names are resolved off the conceptual module name space root.

https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#11.3.1

So the 'FileClass' must be a so called top-level module.
But, the doc didn't explain what is a top-level module.

The first question for me is that what the term top-level means? And what is a conceptual module name space root?

Continue to read the doc, and I found this

If the import declaration specifies a top-level module name and the program contains no AmbientModuleDeclaration (section 12.2) with a string literal that specifies that exact name, the name is resolved in a host dependent manner (for example by considering the name relative to a module name space root). If a matching module cannot be found an error occurs.

This is hard to understand for me. Is there a realworld example for this ?

PS: I'm using TypeScript 1.5

Upvotes: 0

Views: 186

Answers (1)

tomastrajan
tomastrajan

Reputation: 1726

It depends on what module system you use with your compiler. For example if you use --module commonjs you module syntax is converted to node.js module syntax such as var module = require('module'); In that case if you dont use relative path './module' but only module name the dependecy is resolved in node_modules folder. For the AMD it works similar but i dont exactly know what is the root for AMD modules.

Upvotes: 1

Related Questions