Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node / JS create new instance right upon import

I want to make an instance of a class without importing the class first and making new afterwards.

Instead of

var mainClass = require('../dist/main'); // has "class Main { ... }"
var mainInstance = new mainClass();

I want

var mainInstance = new require('../dist/main').Main();

But something with the syntax is wrong.

var main = new require('../dist/main').Main();
                                       ^
TypeError: Class constructor Main cannot be invoked without 'new'

Is this even possible? I use a combination of TypeScript and plain JS.

like image 202
Daniel W. Avatar asked Jan 27 '17 16:01

Daniel W.


People also ask

Can I use both import and require in node JS?

If nodejs thinks you have a CJS file, you cannot use import (that is only for ESM modules). You can also modify the package. json file that controls your particular script (by adding "type": "module" and force your file to an ESM module if you want (which allows you to use . js files as ESM modules).

Does import and export work in node?

Node. js also allows importing and exporting functions and modules. Functions in one module can be imported and called in other modules saving the effort to copy function definitions into the other files.

Should I use import or require in node?

mjs' extension. NOTE: You must note that you can't use require and import at the same time in your node program and it is more preferred to use require instead of import as you are required to use the experimental module flag feature to run import program.


1 Answers

You can use parenthesis to achieve that:

var main = new (require('../dist/main').Main)();

And if your module.exports was solely exporting a class you'd do it like following:

var main = new (require('../dist/main'))();
like image 54
zurfyx Avatar answered Oct 08 '22 09:10

zurfyx