Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict Webpack `require.context` neatly?

I am developing a little static site generator on top of Webpack and React. Currently I'm making it more dynamic. One part of this is making it more configurable.

Given a site structure like this

.
├── _book
├── assets
├── build
├── drafts
├── manuscript
├── node_modules
├── pages
├── project_source
└── styles

I would want to require files only from certain directory or directories. In this case it would be enough to require Markdown files from manuscript. Naively var req = require.context('manuscript', true, /^\.\/.*\.md$/) would work.

The problem is that this needs to become dynamic as I pass the directory through site generator configuration. As require.context relies on fixed values I think I need to change context to site root using something like var req = require.context('.', true, /^.*\.md$/) and then check against req.keys() to match against my configuration.

In practice this is extremely slow as it will traverse the whole tree! Especially node_modules can contain a lot of files and this is something that should be avoided at all costs.

Is there a neat way to exclude node_modules out of require.context? I suppose some form of Regex might work although I am open for other ideas.

like image 256
Juho Vepsäläinen Avatar asked May 12 '15 16:05

Juho Vepsäläinen


1 Answers

You could try:

var req = require.context('.', true, /^((?![\\/]node_modules|vendor[\\/]).)*\.md$/);

to exclude paths containing node_modules and vendor folders from the match.

like image 131
Artem Ivanyk Avatar answered Oct 19 '22 15:10

Artem Ivanyk