webpack require every file in directory

后端 未结 3 1862
予麋鹿
予麋鹿 2020-11-30 02:31

This is my file structure

-main.js
-SomeDir
   -fileA.js
   -fileB.js

What should I do if I want to load (inside main.js) ever

相关标签:
3条回答
  • 2020-11-30 02:50

    Yes, it is possible, even recursively in the folder hierarchy

    Here's a sample:

    var context = require.context('./', true, /\.(html)$/);
    var files={};
    
    context.keys().forEach((filename)=>{
      console.log(filename);
      files[filename] = context(filename);
    });
    console.log(files); //you have file contents in the 'files' object, with filenames as keys
    

    And a live demo here (open up devtools to see the generated object)

    http://www.webpackbin.com/Vy6AwkWrz

    In your case the first line would be

    var context = require.context('./SomeDir', false, /\.js$/);
    

    Reference: https://webpack.github.io/docs/context.html#require-context

    0 讨论(0)
  • 2020-11-30 02:56

    Solution:

    var req = require.context("../someDir", true, /^(.*\.(js$))[^.]*$/igm);
    req.keys().forEach(function(key){
        req(key);
    });
    // or just: req.keys().forEach(req)
    

    extra:

    regex to match js but ignore test.js

    /^(?!.*test.js)((.*\.(js\.*))[^.]*$)/igm)

    0 讨论(0)
  • 2020-11-30 03:01

    One approach could be to create an index.js file in SomeDir location and in that file:

    var req = require.context('./', true, /\.js$/);
    req([]);
    

    Then in main.js:

    require('./SomeDir');
    

    or

    require('./SomeDir/index.js');
    

    or even

    import something from "./SomeDir";
    
    0 讨论(0)
提交回复
热议问题