How to restrict Webpack `require.context` neatly?

I am developing a small static site generator on top of Webpack and React. I am currently making it more dynamic. One of them makes it more customizable.

Given a site structure such as

. β”œβ”€β”€ _book β”œβ”€β”€ assets β”œβ”€β”€ build β”œβ”€β”€ drafts β”œβ”€β”€ manuscript β”œβ”€β”€ node_modules β”œβ”€β”€ pages β”œβ”€β”€ project_source └── styles 

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

The problem is that this should become dynamic as I pass the directory through the node generator configuration. Since require.context relies on fixed values, it seems to me that I need to change the context to the root of the site using something like var req = require.context('.', true, /^.*\.md$/) , and then check on req.keys() so that it matches my configuration.

In practice, it is very slow, as it will pass through the whole tree! Especially node_modules can contain many files, and this should be avoided at all costs.

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

+6
source share
2 answers

I decided to solve the problem by clicking require.context outside the static site generator and in the external configuration. I have such small snippets:

 paths: { demo: { path: function() { return require.context('./demo', true, /^\.\/.*\.md$/); }, } } 

Then on the generator side, I just use these contexts.

This is not the solution I was hoping for, but it works.

0
source

You can try:

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

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

+7
source

Source: https://habr.com/ru/post/987074/


All Articles