Categories
JavaScript Answers

How to pass arguments to require (when loading module) with Node.js?

Spread the love

To pass arguments to require (when loading module) with Node.js, we export a function.

For instance, we write

class MyClass {
  constructor(arg1, arg2, arg3) {}
  myFunction1() {}
  myFunction2() {}
  myFunction3() {}
}

module.exports = (arg1, arg2, arg3) => {
  return new MyClass(arg1, arg2, arg3);
}

in myClass.js to export a function that returns the MyClass instance.

Then we write

const MyClass = require("/myClass.js")(arg1, arg2, arg3);

in app.js to import myClass.js and call its constructor with the arguments.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *