36

This is my file structure

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

What should I do if I want to load (inside main.js) every file in someDir without specifying the file names -

something like: require(./someDir/*.js) ?

Manwal
  • 23,450
  • 12
  • 63
  • 93
yonatanmn
  • 1,590
  • 1
  • 15
  • 21

4 Answers4

49

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)

Community
  • 1
  • 1
yonatanmn
  • 1,590
  • 1
  • 15
  • 21
  • 1
    I got an error when using this approach, any suggestion? Thanks. https://github.com/webpack/webpack/issues/1635 – Hao Nov 16 '15 at 15:42
  • @NickMcCurdy Isn't it the other way round? Webpack 1 and Webpack 2 [both](https://webpack.github.io/docs/context.html) [support this](https://webpack.js.org/guides/dependency-management/#require-context), but it wouldn't work without Webpack... or do I miss something here? – x-ray May 14 '17 at 20:40
  • Sorry I was totally wrong, this was webpack syntax I was unaware of. Deleting my comment. – Nick McCurdy May 14 '17 at 22:17
  • 8
    What's the ES6 version for this require? – dude Jul 04 '17 at 09:56
  • Does anyone know how you'd require multiple directories with this method? – JCraine Sep 22 '19 at 12:27
12

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

Tudor Ilisoi
  • 2,934
  • 23
  • 25
6

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";
VyvIT
  • 1,048
  • 10
  • 13
0

Webpack5 cause "webpack-context-dup-keys" Solution here We have to use below /./.*.md$/ e.g.

 let ctxWrong   = require.context("../content/posts", true, /\.md$/);
 let ctxCorrect = require.context("../content/posts", true, /\.\/.*\.md$/); 

Please look at issue here

Cloud Gem
  • 131
  • 2
  • 2