Amrita Stha
Amrita Stha

Reputation: 3327

Removing log from production mode is not working - react native

React native documentation state that "You can also use this babel plugin that removes all the console.* calls. You need to install it first with npm i babel-plugin-transform-remove-console --save-dev, and then edit the .babelrc file under your project directory like this"

{
  "env": {
    "production": {
      "plugins": ["transform-remove-console"]
    }
  }
}

I didn't find .babelrc file. Hence I made the following changes in babel.config.js file.

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  env: {
    production: {
      plugins: ["transform-remove-console"]
    }
  }
};

But it's not working for me. The logs are displayed when I've tested them in Android Studio. What went wrong here?

Upvotes: 1

Views: 1469

Answers (2)

Kailash Uniyal
Kailash Uniyal

Reputation: 997

This should work (recommended method)

const presets = ['module:metro-react-native-babel-preset'];
const plugins = ['module:react-native-dotenv'];

if (process.env.ENV === 'prod') {
  plugins.push('transform-remove-console');
}

module.exports = {presets, plugins};

Or if you don't want to use any package for this you can do this. Place this in index.js

if(!__DEV__){
   console.log = () => {}
}

Upvotes: 2

Dan Stoppelman
Dan Stoppelman

Reputation: 859

The documented approach didn't work for my existing project either, but it worked in a new test project. I tried numerous dependency upgrades, adding/removing deps, plugins, etc. trying to figure out the source of the problem, but no luck. So finally I went with this workaround:

    module.exports = {
      plugins: ['@babel/plugin-proposal-numeric-separator', 'lodash'].concat(
        process.env.NODE_ENV === 'production' ? ['transform-remove-console'] : []
      ),
      presets: [
        'module:metro-react-native-babel-preset',
        ['@babel/env', { targets: { node: 6 } }]
      ]
    };

Upvotes: 1

Related Questions