2019-09-15
Exclude files from require.context of Webpack
stackoverflow
Question

I'm trying to include in with require.context of Webpack all the files that should be covered by my Istanbul reporter.

I would like to include/require all the files under app that have not the .test.js extension.

// internals/testing/test-bundler.js
const context = require.context('../../app', true, /^.*(?!(\.test|internals.*))\.js$/);
context.keys().forEach(context);

My files structure is:

app/components/
app/containers/
app/decorators/
app/orm/
app/pages/
app/store/
app/tests/
app/utils/
app/app.js
app/reducers.js
app/routes.js
internals/testing/test-bundler.js

Obviously my regex doesn't work because inside the coverage report I see all the .test.js files and even the internals/testing/test-bundler.js file.

What am I doing wrong?

Answer
1

You need to be aware after what part the negative lookahead employs it's rejection. If you do it right after the first forward slash it works fine.

And with that you want to reject .*test after the slash, instead of just test directly behind it.

/^(?!internals).*\/(?!.*test).*\.js$/

Or more specific not allowing internals in the path name.
Nor ending with test.js:

^(?!.*(?:internals|test.js$)).*\.js$
Exclude files from require.context of Webpack
See more ...