How to import module from non-relative paths in Visual studio 2015
Asked Answered
H

1

7

I am working on angular 4 project using gulp in Visual studio 2015. I got the Visual Studio 2015 QuickStart from here.

  • tsc version: 2.5.2

My project structure:

src
└──angular
     └──common
           └──models
                └──items.ts
     └──ui
         └──components
                └──items.component.ts

items.ts

export module items {
  export const listOfItems = [1,2,3];
}

I want to use non-relative path when importing everything within my src folder, i.e.:

items.component.ts

import { items } from 'items';

This is my tsconfig.json file (which is on the same level as src):

{
  "compileOnSave": false,
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "typeRoots": [
      "node_modules/@types/"
    ]
  }
}

I have tried adding this into the compilerOptions:

"baseUrl": "." //it doesn't help.

after that:

"baseUrl": ".",
    "paths": {
      "*": [
        "*",
        "src/angular/*" // still nothing.
      ]
}

I also added rootDirs but I am still getting this error:

Can't find module 'items'
Herd answered 19/9, 2017 at 13:37 Comment(0)
D
6

First, be sure that you have installed TypeScript for Visual Studio 2015 - v2.5.2, after that:

tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./src",
     "paths": {
     "@models/*": [ "angular/common/models/*" ]
     }
    //..
  }
}

usage:

import { items } from '@models/items';

So, what's happening here:

* is pointing to the actual name of our file, so in our case after @models there is * which is pointing to items, and items is somewhere inside angular/common/models/*.

Also, we should add this into systemjs.config.js so that the path can be resolved:

 System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/',
      "@models/*": ["rootDist/angular/common/models/*"]
                        ^
                        where you keep your files, for example dist/
    }
    // other things..
  });

And another important thing here is to restart the visual studio

I've also tried unload/reload the project, but that doesn't help.

Distributary answered 19/9, 2017 at 19:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.