Lee
Lee

Reputation: 1445

How to require entire dir for Webpack or Browserify

I'm learning how to use Webpack and Browserify so I'm still new at this. It seems to me that there should be an easy way to require entire dirs similar to ./dir/**/*.js but that doesn't seem possible. So if I understand correctly, I only have the following options:

Am I missing something?

Upvotes: 1

Views: 288

Answers (1)

katranci
katranci

Reputation: 2571

You could use require.context.

The following code creates a context with any files matching .js$ regular expression within ./dir directory recursively:

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

All files within a context are bundled in webpack output. For example, the file ./dir/foo/bar.js can be loaded like this:

var bar = req('./foo/bar.js');

You can also retrieve a list of files in a context:

req.keys();

Upvotes: 1

Related Questions