I am using node --experimental-modules test.mjs
(NodeJs v11.9.0).
There are many options to implement the same class, and I need to swith by terminal,
Modern Javascript (ES6+) implementations are under construction, some syntax are working with NodeJS (node --experimental-modules
) and good browsers, other not.
This is the only way to do without cost of "load all" (see @Markus solution), but with the cost of non-global import, needs an ugly block to define scope and assyncronous operation... First step is to understand the basic impor block syntax:
import('./MyClass-v3.mjs').then(({default: MyClass}) => {
// can use MyClass only here in this block
let x = new MyClass();
console.log("DEBUG=",x);
});
Them, putting all together, the argv selection and the optional imports.
const classes = {
a: './MyClass-v1.mjs'
,b: './MyClass-v3.mjs'
,c: './MyClass-v3.mjs'
};
import(classes[process.argv[2]] || classes.c ).then(({default: MyClass}) => {
let x = new MyClass();
console.log("DEBUG=",x);
});
PS: some of the magic (no rational) is to use ({default: MyClass})
instead (MyClass)
.
To @Bergi (!), for explain this solution (see question comments).