Is it possible to import modules from all files in a directory, using a wildcard?

前端 未结 13 2039
陌清茗
陌清茗 2020-11-22 04:25

With ES6, I can import several exports from a file like this:

import {ThingA, ThingB, ThingC} from \'lib/things\';

However, I like the orga

13条回答
  •  不思量自难忘°
    2020-11-22 04:37

    The current answers suggest a workaround but it's bugged me why this doesn't exist, so I've created a babel plugin which does this.

    Install it using:

    npm i --save-dev babel-plugin-wildcard
    

    then add it to your .babelrc with:

    {
        "plugins": ["wildcard"]
    }
    

    see the repo for detailed install info


    This allows you to do this:

    import * as Things from './lib/things';
    
    // Do whatever you want with these :D
    Things.ThingA;
    Things.ThingB;
    Things.ThingC;
    

    again, the repo contains further information on what exactly it does, but doing it this way avoids creating index.js files and also happens at compile-time to avoid doing readdirs at runtime.

    Also with a newer version you can do exactly like your example:

     import { ThingsA, ThingsB, ThingsC } from './lib/things/*';
    

    works the same as the above.

提交回复
热议问题