The Optimal Approach for Importing Libraries across Multiple Files

I have two files - one containing the main code execution, and the other solely consisting of a class.

For instance:

File_1:

const _ = require('underscore'),
CoolClass = require('CoolClass');

_.map(//something)

Files_2:

const _ = require('underscore');

class CoolClass(){
  constructor(){
    _.map(//something);
  }
}

What is the correct approach to utilizing external libraries?

Should I include the library in both files or only in the main file and then pass it to the constructor like this:

let cool_stuff = new CoolClass(_);

Alternatively, should I pass it when requiring it, such as:

const _ = require('underscore')(_);

Thank you!

Answer №1

Absolutely! When using Node, it is necessary to include the library in every file independently.

Typically, the loading system, whether it's Node's built-in require or an alternative, will cache the module to avoid repeated reloading from the file system.

This practice allows you to have a separate variable referencing the library in each file.

In certain circumstances, you can opt for the second approach where you import and initialize an object from the library, passing the initialized object afterwards.

For instance, if you are working with a library like underscore which only requires importing and immediate usage, you would still need to require it in each file.

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

Showing no background color until the user lifts their finger

I am currently in the process of developing a website. The navigation on the website starts off as transparent (background: transparent) when opened, but as soon as you start scrolling, it should transition to a colorful state with shades like grey, midnig ...

The offset value was inconsistent in the desktop version of Firefox

Could you take a look at my code on the fiddle link, Here is the code snippet: <body> <div id="content" style="width:400px; height:110px;"> <svg id="circle" height="300" width="300"> <circle cx="150" cy="150" r="40" st ...

What could be the reason that Ng Repeat fails to work when a button is triggered from a separate form

I have an HTML table that includes an ng repeat directive and two buttons. The first button opens a modal with a form to create a new user. When I click save, it adds the new user to the list. The second button is within the same form and also adds a user. ...

Ugly consequences arise as Gulp stumbles upon uncharted territory during the uglify

I'm experiencing an issue with my squish-jquery task. Every time I run it, I encounter the following error: Starting 'squish-jquery'... events.js:85 throw er; // Unhandled 'error' event ^ Error at new JS_Par ...

Encountered a failure while attempting to substitute environment variables in configuration files with the help of Bash and

Trying to integrate a private NPM module into my application is proving to be quite challenging. I need to configure the NPM access tokens correctly so that third-party tools like Heroku and CI can access and install the module. In my ~/.bash_profile, I h ...

Using NPM may lead to segmentation faults

Every time I attempt to use npm in the command line on my Windows 8.1 system, I encounter segmentation faults. Despite multiple attempts at uninstalling and reinstalling node.js using various x64 msi files from the official website, the issue persists. Is ...

Issue encountered during the installation of napi-js or @adonis/cli on NPM

Encountering an error while trying to install Adonis CLI or Hapi-js. It's unclear why this issue is happening on my system, so any insights or suggestions would be appreciated. npm --version 6.8.0 node --version v10.14.2 The error message received ...

What is the best way to add multiple Vue components to my Vue page?

Is there a more efficient way to handle multiple imports without having to write them all out individually? import button1 from './components/button1' import button2 from './componnets/button2' import table1 from './componnets/tabl ...

Getting the local folder name using AngularJs

Is there a way to retrieve the directory name by browsing to a folder and clicking a button? I was considering utilizing <input type="file" /> to achieve this. ...

utilizing Nuxt code in Elixir/Phoenix

Overview In my previous work, I combined frontend development with nuxt and backend support from elixir/phoenix, along with nginx for reverse proxy. Looking to enhance the performance of the system, my goal is now to migrate everything to Elixir/Phoenix. ...

Typescript - Issue with accessing Express Response object

Having trouble using the methods of the Response object in my TypeScript method. When I try to log it, all I get is an empty object. It seems like the import is not providing the response as expected. import { Response } from 'express'; async sen ...

Simplified React conditional rendering made easy

Currently, I am utilizing React 16 with Material-Ui components. In my root component, I have a requirement to load a tab and a view conditionally based on a property. Although I have managed to implement this functionality, the code appears quite messy a ...

What exactly is the purpose of the QueryString function and how does it work

I recently took on the role of editor for a website that I did not create. One of the webpages contains a map feature, and I've been tasked with changing how the map loads initially on the webpage. As I review the JavaScript code, I'm unsure if ...

Using values from a designated line within the textarea to successfully submit a GET form

How can I extract values from a specific line in a TextArea and use them to submit a form? <!DOCTYPE html> <html> <body> <input type='button' value='submit' onclick='document.getElementById("submit-line-3") . ...

Acquiring information from a different Vue.js component

I am faced with a puzzle involving 2 components, A and B. Component A: import B from '../components/B.vue'; export default { components: { B }, methods: { test: function() { console.log(B.data().settin ...

What is the best way to verify a password's strength with Joi so that it includes 2 numbers, 2 special characters, 2 uppercase letters, and 2 lowercase letters?

Is there a way to achieve this using Joi? For instance: Joi.string() .required() .min(8) .max(16) .pattern(/(?=(?:.*[a-z]){2,16}).+/) .pattern(/(?=(?:.*[A-Z]){2,16}).+/) .pattern(/(?=(?:.*[0-9]){2,16}).+/) .pa ...

Unable to display images in the ngImgCrop upload preview modal screen

Currently, I am utilizing ngImgCrop to enable an upload preview and square crop feature for profile pictures. Unfortunately, I am experiencing issues where neither the image preview nor the cropping functionality are being displayed. 'use strict ...

Guide to showcasing console output on a Web Server

Apologies if this question is not the most suitable for this platform. I recently set up Pure-FTPd service on a CentOS server. To check current connections, I use the command pure-ftpwho, which gives me the following output: +------+---------+-------+---- ...

What language should be used for JSON data formats?

I am dealing with a JSON file named myjson.cfg that has the following structure: { "values": { "a": 1, "b": 2, "c": 3, "d": 4 }, "sales": [ { "a": 0, "b": 0, "c": 0, "d": 0, ...

The try/catch block proves ineffective at handling a socket connection exception

I am attempting to test connection to a non-existent socket. In this scenario, an exception is thrown and I anticipate it being caught in the try/catch block below. The function createConnection is imported from the net package. try { createConnection( ...