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

I'm looking to enhance my Angular app by implementing a submenu that features various tabs

Currently, I am following a tutorial available at this link to achieve my desired outcome. However, I am facing some challenges because my tabs are not located in the root component. In my scenario, I have a contract with certain properties that I want to ...

Retrieving data from child components within an array in another component using Angular

How can I assign the value of the variable 5 in Array(5) to another variable in this code? My goal: export class HelloComponent { @Input() page: number; active = 0; pages; constructor() { this.pages = Array(this.page) // instead of Array( ...

The spread operator seems to be malfunctioning whenever I incorporate tailwindcss into my code

Hi there! I hope you're doing well! I've come across a strange issue in Tailwindcss. When I close the scope of a component and try to use props like ...rest, the className doesn't function as expected. Here's an example: import { Butto ...

Passing dynamic values to nested components within an ngFor loop in Angular

I'm currently facing an issue with a child component inside a ngFor loop where I need to pass dynamic values. Here is what I have attempted so far, but it doesn't seem to be working as expected <div *ngFor="let item of clientOtherDetails& ...

Tips for resolving: Dilemma - Angular configuration loaded in both synchronous and asynchronous manner

I recently updated my Angular 6 project to Angular 11. The project includes server-side rendering (SSR), and I am encountering an issue. After running ng run myapp:server, I am getting the following error: ✔ Server application bundle generation complete ...

The global and centered positioning in @angular/cdk/overlay is not functioning as expected

I am currently experimenting with the new @angular/cdk library, but I am having trouble getting the position strategy to work. I simply want to display a modal that is centered on the screen with a backdrop. I know I can apply a class to the pane and use f ...

Automatically log into Google using Angular with Angularx-Social-Login

Utilizing Google sign-in and Angularx-Social-Login to authenticate users has been successful for me. However, I am facing an issue where users have to log in again whenever they reload the page or open a new tab, despite setting autologin: true. I have imp ...

`The dilemma of z-index in a dropdown menu nested within an animated card`

Having an issue that I have attempted to simplify in this StackBlitz example (the actual project is created with Angular components and Bootstrap, etc.): https://stackblitz.com/edit/angular-bootstrap-4-starter-njixcw When incorporating a dropdown within ...

Encountering a problem while implementing ngFor in Angular 4

Issue with ngFor Loop in Angular 4 Does anyone have insight into why this error is appearing in the console despite data being displayed? The data is showing, but an error is still being thrown empresas = <Empresa> {}; constructor(private servi ...

Performing optimized searches in Redis

In the process of creating a wallet app, I have incorporated redis for storing the current wallet balance of each user. Recently, I was tasked with finding a method to retrieve the total sum of all users' balances within the application. Since this in ...

Error in NextJS: Attempting to access a length property of null

Does anyone have insights into the root cause of this error? warn - Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/basic-features/fast-refresh#how-it-works TypeError: Cannot read properties of null (reading 'lengt ...

The proper method for retrieving FormData using SyntheticEvent

I recently implemented a solution to submit form data using React forms with the onSubmit event handler. I passed the SyntheticBaseEvent object to a function called handleSubmit where I manually extracted its values. I have identified the specific data I n ...

Error in Angular2: Method this.http.post is invalid and cannot be executed

import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/catch'; // import 'rx ...

Creating an array of strings using data from a separate array of objects in JavaScript/TypeScript

I want to generate a new array of strings based on an existing array of objects, with each object belonging to the Employee class and having a firstName field: assignees: Array<Employee>; options: string[]; I attempted to achieve this using the fol ...

Unveiling the Mysteries of HTTP Headers in Angular

Seeking a way to retrieve a token set in the http header within my Angular application. This is how my Angular application is being served: var express = require('express'); var app = express(); var port = process.env.PORT || 3000; var router = ...

Guide to sending jQuery data back to main class in TypeScript

Hi everyone, I'm diving into the world of typescript and JQuery. I have a simple question. In my typescript class called DatePicker, I am calling a function. Here's a snippet of the code: Class DatePicker { private pickerData; public update( ...

Retrieve various data types through a function's optional parameter using TypeScript

Creating a custom usePromise function I have a requirement to create my own usePromise implementation. // if with filterKey(e.g `K=list`), fileNodes's type should be `FileNode` (i.e. T[K]) const [fileNodes, isOk] = usePromise( () => { ...

I noticed an excess of white space on the right side of my Angular website

Check out my website here. Everything seems to be functioning correctly, however, there is an issue with scrolling on mobile. It should only scroll up and down, not left and right! I have noticed a strange white space on the right side of my site when view ...

Struggling to connect JSON information to a dynamically loaded sub-component

I'm currently working on dynamically loading a child component from the parent component. The goal is to pass some parameters from the parent to the child, which will then be used in the child component to make a service call and retrieve data from a ...

Ways to update index.html in Angular 8.3+ based on the current environment settings

I am currently developing an application using jhipster, Spring Boot, and Angular. One challenge I am facing is setting up different public keys based on whether the app is running in a development or production environment. I have spent a considerable a ...