Discussing the declaration of dependencies (such as modules) per file reveals a two-sided nature to this practice.
On one hand, the benefit lies in the transparency it provides - there is no ambiguity about where each function, variable, or class originates from. This clarity facilitates identifying which libraries or frameworks are being utilized and pinpointing the source of any troubleshooting issues. Contrasting this with the approach adopted by Ruby on Rails using Ruby Gems, where nothing is explicitly declared and everything is automatically loaded, the difference is stark. From personal experience, deciphering the origin of something like some_random_method
becomes an arduous task, along with determining the available methods and classes.
It is acknowledged that a drawback arises in the potential verbosity resulting from numerous imports and relocating relative files. However, contemporary editors and IDEs such as WebStorm and Visual Studio Code offer features that alleviate this burden by automatically updating the relative paths upon file movements and adding imports when referencing code in another module.
One pragmatic resolution for managing multiple import
s involves creating a 'group' import file. For instance, if a set of utility functions is frequently used across various files, these can be consolidated into a single file and referenced accordingly throughout other files:
// File: helpers/string-helpers.ts
import {toUppercase} from "./uppercase-helper";
import {truncate} from "./truncate-helper";
export const toUppercase = toUppercase;
export const truncate = truncate;
Subsequently, in any other file:
import * as StringHelpers from "../path-to/helpers/string-helpers";
...
let shoutingMessage = StringHelpers.toUppercase(message);
An associated downside is the risk of disrupting tree shaking, wherein tools like webpack discard unused code segments.