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.
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).
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.
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.
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'))();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With