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

前端 未结 13 2276
陌清茗
陌清茗 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:56

    Similar to the accepted question but it allows you to scale without the need of adding a new module to the index file each time you create one:

    ./modules/moduleA.js

    export const example = 'example';
    export const anotherExample = 'anotherExample';
    

    ./modules/index.js

    // require all modules on the path and with the pattern defined
    const req = require.context('./', true, /.js$/);
    
    const modules = req.keys().map(req);
    
    // export all modules
    module.exports = modules;
    

    ./example.js

    import { example, anotherExample } from './modules'
    

提交回复
热议问题