如何在Visual Studio 2015中从非相对路径导入模块

7

我正在使用 Visual Studio 2015 和 Gulp 开发 Angular 4 项目。

我从这里获取了 Visual Studio 2015 QuickStart

  • tsc 版本: 2.5.2

我的项目结构如下:

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

items.ts

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

我希望在导入src文件夹内所有内容时使用非相对路径,即:

items.component.ts

import { items } from 'items';

这是我的tsconfig.json文件(与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/"
    ]
  }
}

我尝试将以下内容添加到compilerOptions中:

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

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

我还添加了rootDirs,但是我仍然收到这个错误:

Can't find module 'items'
1个回答

6

首先,请确保您已经安装了 TypeScript for Visual Studio 2015 - v2.5.2,然后:

tsconfig.json:

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

用法:

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

那么,这里发生了什么:

*指向我们的文件实际名称,在我们的情况下在 @models 之后有一个指向 items*,而 itemsangular/common/models/* 中的某个位置。

此外,我们应该将此添加到 systemjs.config.js 中,以便可以解析路径:

 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..
  });

另一个重要的事情是要重新启动Visual Studio

我也尝试过卸载/重新加载项目,但是没有帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接