如何从.net core 2.1 Angular 6模板中的非相对路径导入ts和scss文件

ToT*_*oTa 6 path sass typescript visual-studio-2017 angular6

我已经创建了一个新的.net core 2.1应用程序angular template,之后我更新了要使用的项目Angular 6.

请注意,该项目与angular cli生成的项目几乎相同

我的项目将有很多组件和服务,因此我不想使用相对路径,而是希望能够使用非相对路径

打字稿

import { WeatherService } from '../../services/weather.service'
Run Code Online (Sandbox Code Playgroud)

我希望能够使用非相对路径,如:

import { WeatherService } from '@app-services/weather.service'
Run Code Online (Sandbox Code Playgroud)

所以我补充道

"baseUrl": ".",
    "paths": {
      "@app-services/*": [ "src/app/services/*" ]
    },
Run Code Online (Sandbox Code Playgroud)

进入 tsconfig.json

整个配置:

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "baseUrl": ".",
    "paths": {
      "@app-services/*": [ "src/app/services/*" ]
    },
    "lib": [
      "es2017",
      "dom"
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

它按预期工作,我可以在每个组件中导入服务,例如:

import { WeatherService } from '@app-services/weather.service';
Run Code Online (Sandbox Code Playgroud)

但是我跑的时候遇到这个错误ng build:

app/components/home/home.component.ts中的错误(3,32):错误TS2307:找不到模块'@ app-services/weather.service'.

怎么解决这个?

注意:里面ClientApp/src/tsconfig文件的另一个扩展名tsconfig.app.json,但是当我在那里添加非相对路径时,导入根本不起作用,不知道为什么会发生这种情况


SCSS

我已经安装了node-sass,我已经更改了所有.css文件.scss,除此之外我还添加了

"stylePreprocessorOptions": {
              "includePaths": [ 
                "./src/common/"
              ]
Run Code Online (Sandbox Code Playgroud)

angular.json

common文件夹中我保留所有全局scss文件:

common
 |
  - _images.scss
  - _colors.scss
Run Code Online (Sandbox Code Playgroud)

另外,将其添加到同一个文件中:

"schematics": {
    "@schematics/angular:component": {
      "prefix": "app",
      "styleext": "scss" // <<---
    }
  }
Run Code Online (Sandbox Code Playgroud)

它适用于相对路径:

@import '../../../common/_images.scss';
Run Code Online (Sandbox Code Playgroud)

不幸的是,我收到此错误:

未申报的变量

当我像这样导入时:

@import '_images'; 
Run Code Online (Sandbox Code Playgroud)

但是 ......但是,它在构建之后工作正常

Asm*_*107 0

尝试这个:

  import { WeatherService } from '~app-services/weather.service'
Run Code Online (Sandbox Code Playgroud)

而不是这个:

import { WeatherService } from '@app-services/weather.service'
Run Code Online (Sandbox Code Playgroud)