Search code examples
javascriptwebpackbabeljsbabel-loader

Can't get babel loader to apply to dependency


A dependency of my project is using arrow functions and I cannot seem to get babel-loader to transpile the external dependency.

My module section looks like

module: {
        rules: [
            {test: /\.(js|jsx)$/, loader: 'babel-loader'}
        ]
    }

I originally had exclude: /node_modules/(?!superagent)/ in the rules object but removed it to make sure it was not a regex issue.

.babelrc

{
  "presets": [
    "@babel/env",
    "@babel/react"
  ]
}

index.js

import superagent from 'superagent'

superagent.get('http://www.google.com')
    .then(result=>console.log('done'))
    .catch(e=>console.error(e));

The offending dependency in this case is superagent

I created a minimal repo with the config that shows the issue https://github.com/ksmith97/WebpackIssue

I am not sure what else there is to try here

Edit: To be clear this is for IE 11 support.


Solution

  • Move the babelrc config directly to babel loader:

    const path = require('path');
    
    module.exports = {
        entry: './index.js',
        mode: 'development',
        devtool: 'source-map',
        output: {
            path: path.resolve(__dirname, 'dist'),
            filename: 'bundle.js'
        },
        module: {
            rules: [{
                test: /\.(jsx?)$/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: [
                            "@babel/preset-env",
                            "@babel/preset-react"
                        ]
                    }
                },
            }]
        }
    };
    

    This issue got me by surprise too, but looking at the docs you'll see this:

    Searching will stop once a directory containing a package.json is found, so a relative config only applies within a single package.

    And in the case of packages inside node_modules, all of them will have their own package.json file, which will make the .babelrc at the root of your project be ignored when the file being compiled is in a package inside node_modules.

    The loader config does not have this limitation.