Should I Configure Babel Through .babelrc or WebPack?

Viewed 884

In my react project, webpack.config.js brings in proposal-class properties like so:

...
module: {
  rules: [
    {
      test: /\.jsx?$/,
      exclude: /(node_modules|bower_components)/,
      use: {
        loader: 'babel-loader',
        query: {
          presets: ['@babel/react', '@babel/preset-env'],
          plugins: ['@babel/proposal-class-properties']
        }
      },
    }
...

By including @babel/proposal-class-properties I'm able to remove the constructors from my React components, etc.

However, the documentation shows plugin-proposal-class-properties in .babelrc as follows (and doesn't mention webpack.config.js at all):

{
  "plugins": ["@babel/plugin-proposal-class-properties"]
}

whereas my .babelrc does not include any plugins at all:

{
  "presets": [
    ["@babel/env", {
      "modules": false
    },
    "@babel/preset-env"]
  ]
}

Is there any effective difference between including the plugins (such as proposal-class-properties) in webpack.config.js as compared to putting them in .babelrc?

1 Answers

You can configure babel through .babelrc or through the babel-loader configuration in webpack. They both work exactly the same.

However, I recommend only using .babelrc for configuring babel. That way it can also work when you run your tests, which usually don't go through webpack and will therefore not have the webpack configuration for babel.

.babelrc:

{
  "presets": ["@babel/preset-env"]
  "plugins": ['@babel/plugin-proposal-class-properties', {'loose': true}]
}
Related