Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: how to NOT use relative paths to import classes?

I am currently working on an Electron app using TypeScript and Angular2, for which I have created many different classes, all in separate files. In order to make the refactoring of my app easier, I would like to not have to use the relative path when importing those classes.
Right now, to import them, I use this syntax: import {Trigger} from './../../trigger/ts/trigger.component';
What I would like to do is use a syntax that looks like this: import {Trigger} from 'trigger.component';
Is that possible?

like image 386
Yann Lelong Avatar asked Jan 28 '16 18:01

Yann Lelong


People also ask

How do you avoid relative paths in TypeScript?

To fix this, all you need is to set a compilerOptions. baseUrl config in your project's tsconfig. json file. So, if we want to make the src folder (which sits at the root of the project) as the base of every import, we can set it like so.

What is relative import in TypeScript?

A relative import is one that starts with / , ./ or ../ .

Do not import exactly from?

The option “Do not import exactly from” allows you to tell the IDE that you don't want any imports that are from the specific path (e.g. @material-ui/core ) or path pattern (e.g. @material-ui/core/** ). The IDE will then use an alternative path if there is one.

What is allowSyntheticDefaultImports?

When set to true, allowSyntheticDefaultImports allows you to write an import like: ts. import React from "react"; instead of: ts.


2 Answers

Better to use below configuration in tsconfig.json

{
  "compilerOptions": {
    "...": "reduced for brevity",

    "baseUrl": "src",
    "paths": {
      "@app/*": ["app/*"],
      "@trigger/*": ["app/trigger/ts/*"]
    }
  }
}

For your case, use can do either import {Trigger} from '@app/trigger/ts/trigger.component'; or import {Trigger} from '@trigger/trigger.component'; or any level of path you can configure.

like image 184
Shivang Gupta Avatar answered Sep 21 '22 12:09

Shivang Gupta


You can create one file, for example: components.ts and in that component reference to all components, like:

export {Trigger} from '../trigger/ts/trigger.component'
export {Cmp} from '../cmp/ts/cmp.component'
...

Than, when you want to load one component, you can do:

import {Trigger} from '../components.ts'

It is good practice for grouping things.

like image 39
Vlado Tesanovic Avatar answered Sep 20 '22 12:09

Vlado Tesanovic