Clement Clement - 1 month ago 5x
TypeScript Question

How to use js modules from non-module files

I'm a beginner at using js modules.

I'm working on a fairly simple web application. It uses typescript and angular 2, which heavily relies on modules.

Most of my app ts files 'import' one or many js modules (usually mostly angular 2 modules).

As I understand, because my app ts files have a top level 'import', they are automatically considered a js module by typescript.

However, I want any of my app ts files to be accessible by any other of my app ts files, without having to 'import' each other. But because they are now modules themselves, ts requires me to do that...

Is it possible?

It seems crazy to me that for each of my app ts file, I should have to declare every other of my app ts files that are used in there (I like to have tiny files with a single class/interface). In addition, this relies on relative paths which breaks as soon as I restructure my folder structure.

Am I thinking about this the wrong way?


Declaring dependencies (e.g modules) for each file is a double-edged sword.

The advantage is that there is no 'magic' - you know exactly where each function, variable, class etc. is coming from. This makes it much easier to know what libraries / frameworks are being used and where to look to troubleshoot issues. Compare it to opposite approach that Ruby on Rails uses with Ruby Gems, where nothing is declared and everything is auto-loaded. From personal experience I know it becomes an absolute pain to try to workout where some_random_method is coming from and also what methods / classes I have access to.

You're right that the disadvantage is that it can become quite verbose with multiple imports and moving relative files. Modern editors and IDEs like WebStorm and Visual Studio Code have tools to automatically update the relative paths when you move a file and also automatically add the imports when you reference code in another module.

One practical solution for multiple imports is to make your own 'group' import file. Say you have a whole bunch of utility functions that you use in all your files - you can import them all into a single file and then just reference that file everywhere else:

//File: helpers/string-helpers.ts

import {toUppercase} from "./uppercase-helper";
import {truncate} from "./truncate-helper";

export const toUppercase = toUppercase;
export const truncate =  truncate;

Then in any other file:

import * as StringHelpers from "../path-to/helpers/string-helpers";
let shoutingMessage = StringHelpers.toUppercase(message);

The disadvantage of this is that it may break tree shaking, where tools such as webpack remove unused code.