I am using Angular to develop my website. And I wanna set a BASE_API
for my project depends on prod
or dev
. Therefore, I add some code in environment
export const environment = {
production: true,
BASE_API: 'http://localhost:3000/',
};
And I wanna use import { environment } from '@environments/environment'
to import instead of import { environment } from '../../../environments/environment';
So I set tsconfig.app.json
just like below
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"module": "es2015",
"baseUrl": "./",
"paths": {
"@angular/*": [
"../node_modules/@angular/*"
],
"@environments/*": [
"../src/environments/*"
]
}
},
}
And my project structure as below
src
app
environments
environment.prod.ts
environment.ts
However, the VSCode shows:
ERROR in src/app/user/article/article.service.ts(3,29): error TS2307: Cannot find module '@environments/environment'.
How can I fix this problem?
This is called alias. Aliasing our app and environments folders will enable us to implement clean imports which will be consistent throughout our application.
To be able to use aliases you have to add baseUrl and paths properties to tsconfig.json file.
So here in your code, just change your baseUrl to
src
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"module": "es2015",
"baseUrl": "src",
"paths": {
"@app/*": ["app/*"],
"@environments/*": ["environments/*"]
}
}
}
Now you can import environment file like:
import { environment } from '@environments/environment
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With