Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is behind the ‘@’ sign in @angular or @types?

I am trying to understand what is behind the ‘@’ sign when I see import statements like below:

Import { Injectable } from ‘@angular/core’;

Or npm cli commands like below:

npm -install –save @types/lodash

The statements or commands are working fine for me, I just want to learn what is happening behind the scene of the @ sign.

Is this '@' a TypeScript feature? or a NPM thing?

A pointer to an in-depth online documentation would be a great help.

like image 546
Allan Xu Avatar asked Dec 24 '22 15:12

Allan Xu


1 Answers

It's a NPM thing called scoped packages. Here is the official doc:

Scopes are like namespaces for npm modules. If a package's name begins with @, then it is a scoped package. The scope is everything in between the @ and the slash.

All scoped packages are stored inside the folder that begins with @. For example, all Angular packages are stored inside the @angular folder in node_modules, whereas if there was no @ scoped identifier and you used angular/core and angular/compiler you would have separate folder for each package. And the same holds for @types package.

How TypeScript import statement recognizes that or integrates with the '@'?

The require function that is used by node can traverse node_modules folder if you use forward slash in the path and it's not limited to scoped packages:

node_modules
   a
      b
         index.js
         module.exports = 3;

m.js
   console.log(require('a/b')); // logs 3

Typescript compiler uses node's statSync function under the hood to check the folder:

function fileSystemEntryExists(path, entryKind) {
    try {
        var stat = _fs.statSync(path);
        switch (entryKind) {
            case 0 /* File */: return stat.isFile();
            case 1 /* Directory */: return stat.isDirectory();
        }
    }
    catch (e) {
        return false;
    }
}

and naturally this function treats forward slash as a path separator. When resolving path typescript compiler prepends node_modules to the path if NODE module resolution strategy is set.

like image 162
Max Koretskyi Avatar answered Dec 28 '22 09:12

Max Koretskyi