How to dynamically select module with modern nodeJS?

后端 未结 2 1433
情话喂你
情话喂你 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: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';.

提交回复
热议问题