How can I use absolute path in an angular cli generated project?
So I have this path : src -> app -> shared
and I would like to write import {} from 'shared/ffdsdf/my.module.ts'
instead of '../shared/ffdsdf/my.module.ts'
better sample:
tsconfig.json
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"@app/*": [
"app/*"
],
"@app/core/*": [
"app/core/*"
],
"@app/shared/*": [
"app/shared/*"
],
"@env/*": [
"environments/*"
]
}
}
}
use:
import { someService } from "@app/core/some.service";
instead of:
import { someService } from "./../../core/some.service";
"C:/xxx/app/*" instead of "app/*" ?There is a TypeScript feature that allows this.
You can modify your src/tsconfig.json file to enable this, under compilerOptions, add the following:
{
"compilerOptions": {
// ...
"paths": {
"*": [
"./*",
"app/*",
"../node_modules/*"
]
}
}
You can obviously change the pattern key and values as needed. You add or remove folders, you can change the order, etc.
You can also choose a prefix instead of just * (especially if it cases problems), you can use something like ~/*, and your imports will then be all from '~/shared/sample' etc.
The easiest way I found is to put this in tsconfig.json
"compilerOptions": {
"rootDir": "src",
"baseUrl": "src"
}
The component will look like this:
import { Thing } from 'app/Thing';
For me adding @ and listing every path looks like a waste of time. This way every project will work the same.
TIP: Restart IDE if getting module not found error, for tsc to restart.
In Angular9, it's important to follow the following steps.
baseUrl and path in tsconfig.json {
"baseUrl": "./src",
"paths": {
"@angular/*": [
"../node_modules/@angular/*"
],
"@app/*": ["app/*"],
"@views/*": ["app/views/*"],
"@containers/*": ["app/containers/*"]
}
}
Note: Here you can see that I have also added @angular path resolution to tsconfig.json. This step will ensure VSCode to show the correct syntax highlighting.
baseUrl and path from tsconfig.app.jsonNote: Without doing this step, you will get the module not found error when compiling the angular project. (Syntax highlighting was fine even without this).
Since I can't comment on a prior post...
In addition to the answer above by valentineProjects...
"compilerOptions": {
"rootDir": "src",
"baseUrl": "src"
}
You might also have to change the VSCode preferences for typescript.preferences.importModuleSpecifier to "non-relative". The default is "shortest" which caused me to still get ./ paths.