Sergei Basharov
Sergei Basharov

Reputation: 53850

Use variables instead of strings with relative paths for a project written in TypeScript

Can I use something like namespaces inside a large project for imports?

For example, instead of

import {formatNumber} from '../../../utils/formatters'

I could use

import {formatNumber} from utils.formatters

I think it could simplify future changes in the structure of the project, when I move some components around and don't have to look for the relative paths to change.

How can I tackle the problem?

Upvotes: 4

Views: 495

Answers (2)

Radim Köhler
Radim Köhler

Reputation: 123861

I would suggest to follow technique called "Barrels" (doc link is from angular2 but it is general concept)

https://angular.io/docs/ts/latest/guide/style-guide.html#!#create-and-import-barrels

So, on a global folder level create a file with all these links (and keep only reference to each file there)

export * from './config';
export * from './entity.service';
export * from './exception.service';
export * from './filter-text';
export * from './init-caps.pipe';
export * from './modal';
export * from './nav';
export * from './spinner';
export * from './toast';

Later, anywhere deep in the folder structure, just keep the reference to this file...

You can have more of them, and even use some kind of inner sub-namespace. E.g. this is an example of the root/global 'ng.ts'

// Detail
export * from "@angular/core";

import * as common from "@angular/common";
import * as http from "@angular/http";
import * as upgrade from "@angular/upgrade";
import * as platform from "@angular/platform-browser-dynamic";

// with sub namespaces
export { common, http, platform, upgrade };

and then this is valid

import * as ng from "../../../ng";

@ng.Component(... // root is 'core'
...
let control = new ng.common.Control(); // 'common' is nested as common

Upvotes: 0

basarat
basarat

Reputation: 275917

when I move some components around and don't have to look for the relative paths to change

FWIW with TypeScript it will be a compile error (that you can fix easily with stuff like path completions https://basarat.gitbooks.io/alm/content/features/autocomplete.html#path-completions) so you are better off than you would be with pure JavaScript.

Can I use something like namespaces inside my large project for imports

No. Currently it requires manual management of file ordering which can quickly turn into a pain : https://github.com/TypeStrong/atom-typescript/blob/master/docs/out.md

More

Having relative file paths is indeed a pain. But that is how some JavaScript module systems work (especially nodejs).

Upvotes: 1

Related Questions