2

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?

ChrisM
  • 1,565
  • 14
  • 24

1 Answers1

6

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
          }
        }
      ]

    ]
  }
}
ChrisM
  • 1,565
  • 14
  • 24
Nino Filiu
  • 16,660
  • 11
  • 54
  • 84
  • 2
    Maybe it would be a good example to show another preset in the presets array to show the syntax. It took me a bit of extra time to find out and can help people in the future. For example a `@vue/app` preset that targets ie:10 – greensin Dec 02 '19 at 09:52