Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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)

over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report

0

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";
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!