babel-plugin-preprocessor not working in React 18 with typescript

631 Views Asked by At

I want to use the babel-plugin-preprocessor to remove console.log() calls from my React application. My application was created using create-react-app and uses Typescript.

I'm following the instructions at https://www.npmjs.com/package/babel-plugin-preprocessor. I installed the pluging:

npm install -D babel-plugin-preprocessor

I added the file babel.config.json to the root of my project, and it has the following contents:

{
"plugins" : [
["preprocessor", {
  "symbols": { "IS_BROWSER": false },
  "directives": { "DEBUG": false }
}]
  ]
  }

The above comes directly from the website, but I've set the two values "false" instead of the default "true" because I want to see the console.log lines removed. The website says to put the above in "the babel configuration file," I'm assuming that means to add a file named babel.config.json to my project root based on this babel page: https://babeljs.io/docs/en/configuration

I then add the following to a *.tsx file in my project:

// #if IS_BROWSER
console.log('Home.tsx IS_BROWSER is true');
// #else
console.log('Home.tsx IS_BROWSER is not true');

I then launch the project on my local host using npm-start. But both lines get printed to my console. I was only expecting the 2nd line to get printed; I expected the first line to be removed.

What am I missing? I'm just assuming that the existence of babel.config.json in my project root will magically make all of this work, but obviously this is not the case.

1

There are 1 best solutions below

2
On

CreateReactApp is not respecting .babelrc file directly as you expect. CreateReactApp has it's built-in babel config, so both .babelrc and babel in package.json will be ignored.

There are over two ways to control CreateReactApp.

  1. CreateReactApp native commander npm run eject. This commander will unzip build-in config to project path, and then you can control it.
  2. craco Create React App Configuration Override, an easy and comprehensible configuration layer for create-react-app. Babel override

Once you eject, you can’t go back!

And then you can add your babel config into package.json, like this:

 "babel": {
    "presets": [
      "react-app"
    ],
    "plugins": [
      [
        "preprocessor",
        {
          "symbols": {
            "IS_BROWSER": true
          },
          "directives": {
            "DEBUG": true
          }
        }
      ]
    ]
  },

And your code will work as you expect.