使用 angular cli 脚手架搭建的项目中,默认没有配置 webpack 路径别名的,这样会导致你写的代码是这样的,路径前面有很多 ../,层级多了脑回路就不够用了。
import { AService } from '../../../services/a.service';
import { BService } from '../../../services/b.service';
设置完别名后,代码就是这样的:
import { AService } from '@app/services/a.service';
import { BService } from '@app/services/b.service';
如何设置呢?打开项目根目录中 tsconfig.json,在 compilerOptions 节点下添加 paths
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@app/*": [ "src/app/*" ],
"@services/*": [ "src/app/services/*" ],
"@pipe/*": [ "src/app/pipe/*" ]
}
}
}
注意参数
baseUrl的设置,是相对于tsconfig.json的目录。因为tsconfig.json在项目的根目录下面,你要映射@app/*需要在路径上面添加src,具体要根据你项目的路径配置和需求自定义。另外如果别名后面不加*,比如"@app": [ "src/app" ]是不生效的。













网友评论