How can I introduce something like 'my-app-name/services'
to avoid lines like the following import?
import {XyService} from '../../../services/validation/xy.service';
In TypeScript 2.0 you can add a baseUrl
property in tsconfig.json
:
{
"compilerOptions": {
"baseUrl": "."
// etc...
},
// etc...
}
Then you can import everything as if you were in the base directory:
import {XyService} from "services/validation/xy.service";
On top of this, you could add a paths
property, which allows you to match a pattern then map it out. For example:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"services/*": [
"services/validation/*"
]
}
// etc...
},
// etc...
}
Which would allow you to import it from anywhere like so:
import {XyService} from "services/xy.service";
From there, you will need to configure whatever module loader you are using to support these import names as well. Right now the TypeScript compiler doesn't seem to automatically map these out.
You can read more about this in the github issue. There is also a rootDirs
property which is useful when using multiple projects.
I've found it can be made easier by using "barrels".
index.ts
file.Example
In your case, first create a file called my-app-name/services/validation/index.ts
. In this file, have the code:
export * from "./xy.service";
Then create a file called my-app-name/services/index.ts
and have this code:
export * from "./validation";
Now you can use your service like so (index
is implied):
import {XyService} from "../../../services";
And once you have multiple files in there it gets even easier:
import {XyService, MyOtherService, MyOtherSerivce2} from "../../../services";
Having to maintain these extra files is a bit more work upfront (the work can be eliminated using barrel-maintainer), but I've found it pays off in the end with less work. It's much easier to do major directory structure changes and it cuts down on the number of imports you have to do.
Caution
When doing this there's a few things you have to watch for and can't do:
import {XyService} from "../validation";
). I've found this and the first point can lead to errors of imports not being defined.