How to dynamically select module with modern nodeJS?

后端 未结 2 1424
情话喂你
情话喂你 2021-01-27 22:08

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,

2条回答
  •  囚心锁ツ
    2021-01-27 22:29

    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.

    Solution

    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).


    Thanks

    To @Bergi (!), for explain this solution (see question comments).

提交回复
热议问题