0

I am referencing a file in my component using different paths.

import { environment } from 'src/environments/environment';

or

import { environment } from '../../../../environments/environment';

Both of them are working, but first way is more easy to use.

But may be any issue in production for first path? for example src/file not found.

barteloma
  • 6,403
  • 14
  • 79
  • 173
  • No, because it is resolved when creating the (production) build. It may be different for assets (such as images) referenced in templates or styles though. – rveerd Sep 11 '20 at 09:33

1 Answers1

0

ABSOLUTE VS. RELATIVE PATHS/LINKS

When importing modules in typescript they are usually separated in two:

  • Importing libraries modules, which is quite nice, since we use only the name and they are resolved from node_modules folder
  • Importing modules from our own application

When importing modules from our own application there are two way of addressing

  • Relative Paths e.g: import { environment } from '../../../../environments/environment';
  • Absolute Paths e.g: import { environment } from 'src/environments/environment';

There are full of examples that use relative paths but it goes quickly wrong when the file we need is several levels up or down. Then we get something like:

import { foo } from ‘../../../../bar’;

Since TypeScript 2.0, we have an awesome compiler setting called baseUrl, and we can configure it in the tsconfig.json file like:

{
  "compilerOptions": {
    "baseUrl": "./src"
  }
}

By this way you can use absolute path like this:

import { foo } from ‘app/bar’

For more information about absolute paths check this quick guide: Use absolute paths for module imports

In addition, there is similar discussion here:

Avoiding relative paths in Angular CLI

& check both thees answers of this question:

https://stackoverflow.com/a/41460972/4185370

https://stackoverflow.com/a/43319965/4185370

So, as a conclusion the first one absolute paths are better, but with the right configuration through tsconfig.json.

ng-hobby
  • 2,077
  • 2
  • 13
  • 26