How to dynamically select module with modern nodeJS?

后端 未结 2 1425
情话喂你
情话喂你 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).

    0 讨论(0)
  • 2021-01-27 22:30
    import ClassV1 from './MyClass-v1.mjs';
    import ClassV2 from './MyClass-v2.mjs'; 
    import ClassV3 from './MyClass-v3.mjs';
    
    const classes = {
      a: ClassV1,
      b: ClassV2
    }
    
    const Class = classes[process.argv[2]] || ClassV2;
    

    You could also write an index file with all the classes and do an import * as classes from 'classes.mjs';.

    0 讨论(0)
提交回复
热议问题