How do you configure babel to run with different configurations in different environments How do you configure babel to run with different configurations in different environments reactjs reactjs

How do you configure babel to run with different configurations in different environments


Set up different environments in your .babelrc

{  "env": {    "dev": {       "presets": ["es2015"],       "plugins":["x"]     },    "test": {      "presets": ["es2015"]    }  }}

And then run babel after you have set your BABEL_ENV

BABEL_ENV=test <commandhere> or BABEL_ENV=dev <commandhere>

If you don't set BABEL_ENV, babel will use the NODE_ENV value.If you don't set either BABEL_ENV nor NODE_ENV, it will use 'development'.

CODE BELOW:

function getEnv(defaultValue = "development") {  return process.env.BABEL_ENV || process.env.NODE_ENV || defaultValue;}


Here's an alternative approach to sharing/alternating configurations based upon the current NODE_ENV:

package.json

"scripts": {  "build": "NODE_ENV=production next build",  "dev": "NODE_ENV=development next dev",  "test" : "NODE_ENV=test jest"   ...etc}

babel.config.js (must be a .js file)

const { NODE_ENV } = process.env;const inProduction = NODE_ENV === "production";const inDevelopment = NODE_ENV === "development";module.exports = api => {  /*     alternatively, you can utilize api.env() to get the current NODE_ENV:    const inProduction = api.env("production");    const inDevelopment = api.env("development");    if using api.env(), then these must be defined before invoking the cache  */  api.cache.using(() => process.env.NODE_ENV);  return {    presets: ["next/babel"],    plugins: [      [        "styled-components",        {          ssr: true,          displayName: inDevelopment,          preprocess: inProduction,        },      ],      ["import", { libraryName: "antd", libraryDirectory: "lib" }],      inProduction && "react-remove-properties",    ].filter(Boolean), // this will filter any falsy plugins (such as removing react-remove-properties when not in production)  };};