Reputation: 7802
Edit: Although this question was originally asked about services and I now know that services should be included in modules, the core issue was still valid when applied to importing modules too. There is an updated answer below with the "official" way to do this now that the docs have (somewhat) evolved.
I have a service that I'd like to reference in my module/component. All of my services are in the /_services directory, and I don't want to have to traverse backwards down the file system when I know that my service is always going to be just off the root. If I move my component into a new subdirectory I'd like it to be resilient to this simple change and not require rework.
In other words, can I change this:
import { ApiService } from './../../_services/api.service';
into something like this?
import { ApiService } from '$APP_ROOT/_services/api.service';
Upvotes: 1
Views: 19350
Reputation: 7802
Only a few months later and there's now an answer directly from the angular guide. You can reference modules from the root by using the absolute path starting with "app". For example, if you want to load the shared module you simply use this import:
import { SharedModule } from 'app/shared/shared.module';
Here it is as used in the Guide:
https://angular.io/guide/ngmodule#app-routing
There is also a section about this in the TypeScript guide:
https://www.typescriptlang.org/docs/handbook/module-resolution.html
Upvotes: 2
Reputation: 6546
You could use some libs that are allowing you to do this.
If you are using Webpack check this answer it will resolve your problem
Webpack 1
resolve: { root: [ path.resolve(__dirname + '/src') ] }......
Webpack 2
resolve: { modules: [ path.resolve(__dirname + '/src'), path.resolve(__dirname + '/node_modules') ] }.....
After that you can use
import configureStore from "store/configureStore";
instead of the:
import configureStore from "../../store/configureStore";
If you are not using Webpack you can simply install Babel Root Import
// Usually import SomeExample from '../../../some/example.js'; const OtherExample = require('../../../other/example.js'); // With Babel-Root-Importer import SomeExample from '~/some/example.js'; const OtherExample = require('~/other/example.js');
Upvotes: 0