Search code examples
javascriptwebpackbabeljsbabel-loader

How to properly override babel@7 plugins for separate webpack server/client configurations


I'm using a single .babelrc config and using it in webpack.config.client.js and webpack.config.server.js with babel-loader.

.babelrc:

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "useBuiltIns": "usage",
        "debug": false,
        "modules": false,
        "loose": true
      }
    ],
    "@babel/react"
  ],
  "env": {
    "development": {
      "plugins": ["react-hot-loader/babel"]
    },
    "production": {}
  }
}

The problem is, react-hot-loader find it's way into compiled server code. I did some research and I see that babel 7 allows to configure overrides for such case.

I tried to implement it, but the "env" part never gets overridden:

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "useBuiltIns": "usage",
        "debug": false,
        "modules": false,
        "loose": true
      }
    ],
    "@babel/react"
  ],
  "env": {
    "development": {
      "plugins": ["react-hot-loader/babel"]
    },
    "production": {}
  },
  "overrides": {
    "include": "./src/server/index.js", // ?
    "env": {
      "development": {
        "plugins": [] 
      }
    }
  }
}

Appreciate any help


Solution

  • Babel doesn't know anything about your client/server differentiation. Your "include": "./src/server/index.js", check would affect that single file, but not your conceptual server bundle.

    Realistically, there are a bunch of ways to do this, but I'll just list a couple to start.

    One would be to use env and have 4 instead of 2 (production-client, production-server, development-client, development-server). Then you could do

    "env": {
      "development-client": {
        "plugins": ["react-hot-loader/babel"]
      },
    }
    

    Alternatively, you could set another environment variable, e.g.

    cross-env NODE_ENV=development BUNDLE_NAME=server webpack --config webpack.config.server.js
    

    and rename your config to be a .babelrc.js file, and do

    module.exports = {
      "presets": [
        [
          "@babel/preset-env",
          {
            "useBuiltIns": "usage",
            "debug": false,
            "modules": false,
            "loose": true
          }
        ],
        "@babel/react"
      ],
      "env": {
        "development": {
          "plugins": 
            process.env.BUNDLE_NAME === "server" 
              ? [] 
              : ["react-hot-loader/babel"]
        },
        "production": {}
      },
    };