Choosing between direct imports and package imports in JavaScript

Question: Seeking feedback on the preferred import/export/usage system in TypeScript. While direct imports (#1) are common, which approach is considered best practice in well-established production codebases?

Context: Having worked on large-scale projects in TypeScript and Go, I have primarily used approach #1 but am exploring package-based imports more recently. TypeScript typically favors direct imports, whereas Go leans towards packages. Personally, I lean towards the package approach (#2a or #2b), but I'm curious about the general consensus on whether direct imports (#1) are superior. Any insights on the recommended practice for scalability would be appreciated. ** Direct Import Example:**

File: /services/aws/api-gateway/createAPIGateway.ts

Function Name: createAPIGateway()

Index.ts:

import createAPIGateway from './createAPIGateway';
export { createAPIGateway };

Usage:

import { createAPIGateway } from './services/aws/api-gateway/index';
createAPIGateway();

2a. Package Import Example 1:

File: /services/aws/api-gatewaycreateAPIGateway.ts

Function Name: createAPIGateway()

Index.ts:

import createAPIGateway from './createAPIGateway';
export const apigateway = { createAPIGateway }

Usage:

import { apigateway } from './services/aws/api-gateway/index';
apigateway.createAPIGateway();

2b. Package Import Example 2:

File: /services/aws/api-gateway/create.ts

Function Name: create()

Index.ts:

import create from './create';
export const apigateway = { create }

Usage:

import { apigateway } from './services/aws/api-gateway/index';
apigateway.create();

This inquiry pertains to industry best practices.

Answer №1

There isn't a one-size-fits-all solution to every problem, It all boils down to your individual code and what works best for you, When using approach #1, the createAPIGateway variable is captured within that specific function, prohibiting its use elsewhere unlike in 2a where there are no such restrictions,

Furthermore, approach 2a indicates clearly that it is a function imported from another file rather than being defined within the same file

Ultimately, the "right" way varies based on personal preference.

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

combine array elements with corresponding timestamps

I am working with an array of objects that contain timestamps, as shown below. While I have no issues rendering it in React, I am struggling to figure out how to group and sort the data effectively. const data = [ { id: 0, timeStamp: 1619627889000, title: ...

Using React and Redux: Sending a function to a child component, triggering it without a handler in the child component

I am experiencing difficulty sending an action through a callback in the code provided below. The action is not being sent as expected. However, if I add the Connected property to a handler like onClick, then the action is executed. How can I make my code ...

Invoking a .js file within an UpdatePanel from the CodeBehind

I have been dedicating my time to self-teach ASP.NET and JavaScript for a project, and I've hit a roadblock that has consumed dozens of hours. After discovering a fantastic drag-and-drop JavaScript list online, I copied the provided source code and o ...

Normalization of Firebase Database

Recently, I developed a Tricycle Patrol app designed to address the prevalent issue of reckless tricycle drivers in our city. Users can log in and submit reports through a form that includes fields such as: - created_at - description - lat - lng - plateNu ...

"Extracting JSON data from a URL and loading it into a

I am currently working on a project where I am retrieving data from a URL and storing it in an array. Here is the code snippet: $url = 'https://www.datastro.eu/api/explore/v2.1/catalog/datasets/orbits-for-current-comets-in-the-mpc-database/records?ord ...

Is there a way to create a hover effect on a sidebar element?

I'm struggling to add a hover effect to the elements within my sidebar. I've tried using CSS :hover, but it doesn't seem to be working as expected. Any guidance or solution would be greatly appreciated. .sidebar .navbar .nav-link:hover{ ...

What could be the reason for not receiving any response from my Firestore query?

Hey there! I'm delving into the world of Firebase for the first time and just set up the Firestore emulator. I've added some data that I want to fetch in my Nextjs app. Once I initialized firebase, this is what my component code looks like: funct ...

Steps to configure ExpressJS to listen on a custom domain

I'm trying to set up ExpressJS to listen on a specific domain, as I just acquired a new domain. I want Express.JS to be able to listen on this domain without specifying any ports. Can anyone provide guidance on how to accomplish this? If Express doesn ...

adjusting the height of a div using jQuery UI's layout feature

Recently, I have been playing around with the adjustable grids plugin (jquery ui layout) to set the width of each div using the plugins. However, I've encountered a challenge when it comes to adjusting the height of inner divs within the layout. Speci ...

Creating a function to dynamically assign a class to multiple buttons when a specific button is clicked

I am working on a nuxt.js web application where I have both static and dynamic buttons. When the static button is clicked, I want to add a specific class to each dynamic button. Currently, the code I have is able to add the class to the first dynamic butt ...

Getting data from a URL and passing it as an argument to a ColdFusion function

I am currently utilizing JQuery and AJAX combined with ColdFusion. Within the URL http://mysitedomain.com/something/page.cfm?x=229, there is a value of x that I would like to use as an argument in my ColdFusion function. Could someone kindly explain how I ...

The addition of one hour to the date time format increases the total time

Currently, I am retrieving a datetime column value from a database table as 2015-03-04 21:00:00 UTC. When attempting to convert this format into a datetime picker, the following code is used: date = moment($("#event_start").val()); // date time value fro ...

Retrieve the assigned value of a textbox using a JavaScript function

I'm currently using the script below: <script type="text/javascript"> $(document).ready(function () { $("#<%=txtEnd.ClientID %>").dynDateTime({ showsTime: true, ifFormat: "%Y/%m/%d %H:%M", ...

Using TypeORM to update a relation and set it to NULL

My challenge involves managing this specific Entity @Entity({ name: 'orders' }) export class Order { ... @ManyToOne(() => BulkOrder, (bulkOrder) => bulkOrder.orders) bulkOrder?: BulkOrder } In my update process, I am attempting to re ...

Retrieve a prepared response from a TypeORM query

I need to retrieve all the courses assigned to a user with a simple query: There are 2 Tables: students & courses return await this.studentsRepository .createQueryBuilder('s') .leftJoinAndSelect('courses', 'c' ...

Tips for assigning array variables to elements in querySelectorAll [Pure JavaScript]

I need help with assigning values from an array to elements selected by the querySelectorAll function. I am trying to write code that will change the text to different values in the array when the browser width is below 768px, but I'm facing some chal ...

Accessing the form element in the HTML outside of the form tag in Angular 2

I am attempting to achieve the following: <span *ngIf="heroForm?.dirty"> FOO </span> <form *ngIf="active" (ngSubmit)="onSubmit()" #heroForm="ngForm"> <div class="form-group"> <label for="name">Name</label& ...

Find an idle event loop

Can you check for an idle event loop? Take these two examples: // Example 1 setInterval(() => console.log("hi"), 1000); // event loop not empty // Example 2 console.log("hi"); // event loop is now clear ...

Guidance on invoking the navigate function from a component displayed at the highest level of rendering

Within the react-navigation documentation, it is explained that you can initiate navigation from the top-level component using the following method: import { NavigationActions } from 'react-navigation'; const AppNavigator = StackNavigator(SomeA ...

Having trouble with missing jQuery form serialize data in CodeIgniter when using TinyMCE?

I have encountered an issue while using tinymce. I am sending data through a jQuery ajax call like this: // update textarea from tinymce tinyMCE.triggerSave (false,true); $.post ('', $('#page_form').serialize (), function (x){ var ...