Is importing all models into every component considered poor practice?

At my workplace, there is a practice in the legacy code where every single model is imported into all components, regardless of whether they are needed or not. For example:

import * as models from '../../view-models/models'
.......
let parrot: models.Bird;

Instead of importing only the necessary models in each component, all models are exported in models.ts like this:

export * from './Bird'
export * from './Mammal'
export * from './Amphibian'
.......

In my opinion, it would be more efficient to selectively import only the required models for each component. I am curious if there are any advantages or disadvantages to the current approach?

Answer №1

It is not advisable to import unnecessary modules in a component. It's best practice to only import the required modules.

In your example, you are importing modules that are not needed everywhere.

Step 1

A better approach would be to create named exports directly from the model files themselves. This way, not everything will be exported from the file.

For example, a file like bird.model.ts could have the following structure:

export interface Bird {
  birdId: number;
  birdName: string;
}

Step 2

If you place all these interfaces inside a folder (let's say named model), you can create an index.ts file within the model folder. The content of this file would look like this:

export { Bird } from './bird.model'
export { Mammal } from './mammal.model'
export { Amphibian } from './amphibian.model'

Instead of exporting everything using *, we are now specifically exporting the model interface names.

Step 3

When a Component needs to use a specific model (such as Bird), there are two ways to import it.

import { Bird } from './models';

This will load all exports from the index.ts file in the models folder and then import Bird.

However, if you only require Bird, you can go one level deeper and import Bird directly from ./model/bird.model, like this:

import { Bird } from './models/bird.model';

This method ensures that only what is exported by bird.model is loaded, instead of everything in the index.ts file in the models folder, before importing Bird.

I hope this explanation clarifies how it works for you.

You can also refer to this Sample StackBlitz for reference.

Answer №2

Regarding your inquiry about the potential advantages or disadvantages of approaching it that way:

While it may seem convenient to have all models housed in a single file, taking shortcuts is not always the best approach.

An Angular technique known as Barreling can aid in organizing components and modules effectively, a method often employed by major third-party developers for simplified code importing.

However, consideration should also be given to the programming principle of YAGNI. Why import multiple model classes into every component when only one or two are necessary?

So, is there an advantage? Partially.

Is this considered standard practice? Not particularly.

Ultimately, the decision on whether this approach is beneficial rests with you and your team.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In Angular 15, CSS override configurations do not function as intended

Exploring the world of Angular is exciting, and I am a newcomer to it. Currently, I am tackling an innovative Angular 15 project that makes use of the Material library. My current predicament lies in the fact that none of the CSS overrides appear to be tak ...

The functionality of the Angular directive ngIf is not meeting the desired outcome

We are currently working on transferring data from one component to another using the approach outlined below. We want to display an error message when there is no data available. <div *ngIf="showGlobalError"> <h6>The reporting project d ...

AuthGuard in Ionic 4 causing delay in page routing permissions

In my ionic 4 app, I store user information natively. The goal is to direct users to the Home Page if their information is already stored when they open the app. If not, they should be routed to the Login Page - pretty standard procedure. However, the iss ...

An issue was encountered during the prerendering of the page "/". For more information on this error, visit: https://nextjs.org/docs/messages/prerender-error Attempting to adjust the request (unable to determine

It's been four days and I'm still stuck. I've seen some suggestions to use axios and set the timeout or switch from HTTP to HTTPS when fetching data, but nothing has worked. I'm now four days behind deadline and the client is not going ...

Intercepting 401 with Angular 5 HTTP Interceptor recognizes it as status code 0

One issue I am currently facing is the inability to intercept a 401 status and redirect to the login page, which is a common practice in most applications. My interceptor code seems pretty standard: intercept(request: HttpRequest<any&g ...

TypeScript's type inference feature functions well in scenario one but encounters an error in a different situation

I recently tried out TypeScript's type inference feature, where we don't specify variable types like number, string, or boolean and let TypeScript figure it out during initialization or assignment. However, I encountered some confusion in its be ...

Unable to locate component property

When passing props to my component that link to storybook, I encountered an issue where the object I pass in does not map, resulting in the error message: "TypeError: data.map is not a function". I realized that my object is not actually an &qu ...

Enhancing Angular version from 5.2.7 to 5.2.10

After creating an Angular project using an older CLI version, the default installation was Angular version 5.2.7. Now, I am looking to upgrade my application to the latest stable Angular build, which is 5.2.10. One of the main challenges I'm facing i ...

Effortlessly adding custom classes in Angular 2 with a breeze

Imagine having a growing Angular2 typescript solution with numerous small classes and objects. Following the best practice, each class is placed in its own file. However, manipulating these objects leads to long lists of imports like: import {Object1} f ...

Exploring JSON data in Angular 2

Struggling to comprehend how to navigate through different parts of a JSON object in Angular2. I have a custom web API that provides details about the hard drive on my server, as shown in the JSON object below: https://i.sstatic.net/x1d6M.jpg The image d ...

Exploring Query Parameters in Angular 4

Is it possible to generate a custom URL in Angular 4? For instance: http://localhost:4200/#/page/page2/6/abc/1234 Currently, I am utilizing query parameters like this: this.router.navigate(['page/page2/' + row.id],{ queryParams: {'name&a ...

Tips for creating PrimeNG tables with columns that automatically adjust in size

Is there a way to automatically adjust and resize the columns in my PrimeNG table? I'm looking for a method to make this happen. Can you help me achieve this? ...

Is there a way to modify a single object within an array?

Here is the HTML representation of my data: https://i.sstatic.net/VbKQ4.png page.html <ul id="elements"> <li *ngFor="let elem of fetchdata" (click)="log(elem)"> {{elem.title}} {{elem.description}} </li> ...

Steps to simulate an injected service within a function using Injector

There is an implementation in Angular 7.x where a global error handling injects its services using the Injector. Each function has a reference with the injector, as shown below: import { ErrorHandler, Injectable, Injector, NgZone } from '@angular/co ...

Struggling with VSTS crashing during NPM Install?

My VSTS Batch Script looks like this: cd (my UI dir) echo npm install... npm install echo ng build --output-path %1\ui ng build --output-path %1\ui echo npm run ng build --output-path %1\ui npm run ng build --output-path %1\ui echo All ...

App that uses Angular 2 for real-time data refreshing

As a newcomer to Angular and Nodejs, I am venturing into the development of a MEAN stack cryptocurrency exchange application. My approach involves setting up a nodejs backend to retrieve the current exchange rate from an API and presenting it in the HTML. ...

Unable to retrieve the request body with bodyParser

I am currently working on a NextJS React Application. Within my server/index.tsx file, I have the following code: import next from 'next'; import express from 'express'; import compression from 'compression'; import bodyParser ...

Embracing the "export ... from" feature in the TypeScript compiler

Can the tsc compiler handle this particular export statement? export {PromiseWrapper, Promise, PromiseCompleter} from 'angular2/src/facade/promise'; Your assistance is greatly appreciated! ...

Counting up in Angular from a starting number of seconds on a timer

Is there a way to create a countup timer in Angular starting from a specific number of seconds? Also, I would like the format to be displayed as hh:mm:ss if possible. I attempted to accomplish this by utilizing the getAlarmDuration function within the tem ...

Utilizing Vue and Typescript for efficient dependency injection

After attempting to use vue-injector, I encountered an issue as it was not compatible with my version of Vue (2.6.10) and Typescript (3.4.5). Exploring other alternatives, there seem to be limited options available. Within the realm of pure typescript, t ...