Module parse failed error with webpack & babel-loader

I had a frustrating error recently when running webpack to compile my code using the webpack loader, babel-loader.

My error in the console was similar to the following:
Module parse failed: /directory/file.js Unexpected token (line number) You may need an appropriate loader to handle this file type

There were many StackOverflow questions, but none quite fit the bill for me. This had me stumped for ages.

My webpack.config.js file looked like this:

module.exports = {
    entry: './app/index.js',
    output: {
        path: __dirname + '/public',
        filename: 'bundle.js'
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /(node_modules|test)/,
                loader: 'babel-loader'
            }
        ]
    }
};

I had all the relevant presets and plugins inside my .babelrc file, so that wasn’t the problem:

{
  "plugins": [
    "transform-es2015-modules-commonjs"
  ],
  "presets": [
    "react"
  ]
}

Solution

In my webpack.config.js file, as part of the exclude regex, I listed ‘test’ (/(node_modules|test)/). This was the cause. Removing the word ‘test’ from the regex fixed the issue!

webpack doesn’t like it when one of the exclusions is named ‘test’. I haven’t looked into why.

Leave a Reply

Your email address will not be published. Required fields are marked *