How to exclude webpack from bundling .spec.js files

Although the accepted answer is technically correct, you shouldn't need to add this regex to your webpack configuration.

This is because webpack only compiles the files that are referenced via require or import and so your spec.js files won't be included in the bundle as they are not imported anywhere in the actual code.


Since /\.js$/ allows all .js files (as it basically matches .js at the end of the string), and you need to allow all .js files with no .spec before them, you need a regex with a negative lookahead:

/^(?!.*\.spec\.js$).*\.js$/

See this regex demo

Details:

  • ^ - start of string
  • (?!.*\.spec\.js$) - the line cannot end with .spec.js, if it does, no match will occur
  • .* - any 0+ chars other than linebreak symbols
  • \.js - .js sequence
  • $ - end of the string.