yonatanmn
yonatanmn

Reputation: 1600

webpack require every file in directory

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) ?

Upvotes: 36

Views: 44197

Answers (4)

Cloud Gem
Cloud Gem

Reputation: 181

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

Upvotes: 0

yonatanmn
yonatanmn

Reputation: 1600

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)

Upvotes: 49

Tudor Ilisoi
Tudor Ilisoi

Reputation: 2944

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

Upvotes: 11

VyvIT
VyvIT

Reputation: 1098

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";

Upvotes: 6

Related Questions