Search code examples
javascriptwebpackbabeljsbabel-loaderbabel-preset-env

Defining multiple babel preset configurations in webpack config


I have created a webpack.config.js file that is exporting two different WebPack configuration objects. I need to set up different babel options for presets within these . After a bit of research I have tried creating two different loader configs, each passing a different targets option to the presets like so:

// default JS loader config for browsers that support <script type='module'
{
    loader:'babel-loader',
    options:{
        presets: ['@babel/preset-env', {
            targets: {
                esmodules: true
            }
        }]
    }
}
...


// fallback for browsers that load the <script nomodule 
{
    loader:'babel-loader',
    options:{
        presets: ['@babel/preset-env', {
            targets: "> 0.5% in UK, last 2 versions, not dead, ie 11"
        }]
    }
}

However I am clearly going about this wrong because I get this error on WebPack build

ERROR in ./some-path/WorkflowStage.class.js
    Module build failed (from ./node_modules/babel-loader/lib/index.js):
    ReferenceError: [BABEL] e:\some-path\WorkflowStage.class.js: Unknown option: .targets. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.

I think the crux of the question is: how should I be passing the target option to @babel/preset-env from within my webpack.config.js file when I have multiple presets?


Solution

  • Basically your loader options must look like a JS-encoded .babelrc. Each preset with options must be in it's own array.

    So, replace

    {
      loader: 'babel-loader',
      options: {
        presets: [
          // defines the @babel/preset-env as the first preset
          '@babel/preset-env',
          // defines an invalid object as a preset (throws error)
          { targets: { esmodules: true } }
        ]
      }
    }
    

    with

    {
      loader: 'babel-loader',
      options: {
        presets: [
    
          // defines a preset with options
          [
            '@babel/preset-env', {
              targets: {
                esmodules: true
              }
            }
          ]
    
        ]
      }
    }