如何在使用 create-react-app 创建的 React 应用程序的生产构建中删除 console.log?

How can remove console.log in the production build of a React application created using create-react-app?

如何在使用 create-react-app CRA 创建的 React 应用程序的生产构建中删除 console.log?

问题的简单解决方案是帮助面临同样问题的其他人。

参考:

参考中的建议,需要在文件“webpack.config.js”中进行更改。 create-react-app 在内部使用 webpack 和配置文件,但无法在我的应用程序根目录中添加 webpack.config.js 来应用更改。这将需要离开 create-react-app 设置并为 webpack 和配置构建自己的设置。经过大量探索和编写示例代码后,我发现这并不容易。

因为我很满意create-react-app所以也不想撇开它的好处

最后,我在 node_modules/react-scripts/config/webpack.config.js 中做了一个简单的更改,添加了一行 drop_console: true,,如参考资料中所述。参考中建议的代码如下,

module.exports = {
  optimization: {
    minimizer: [
      new TerserPlugin({
        sourceMap: true, // Must be set to true if using source-maps in production
        terserOptions: {
          compress: {
            drop_console: true, // << this needs only to remove console.log //
          },
        },
      }),
    ],
  },
};

这对我来说很好,通过简单的更改,我的生产构建应用程序中没有控制台日志。

我正在使用 "react-scripts": "3.0.1",

注意:此新行将在您以后重新安装“react-scripts”时被清除。所以它需要在这种情况下再次做同样的改变。

重要提示:如果使用 CI/CD

,请勿使用此方法

我创建了一个 helper 文件夹,其中包含一个名为 ConsoleHelper.js

的文件
const ConsoleHelper = (data) => {
  if (process.env.NODE_ENV === 'production') return;
  console.log(data);
}

export default ConsoleHelper;

所以,而不是 console.log(data)ConsoleHelper(data);

简单的方法是在根目录下创建一个新文件,命名为logger.js

在logger.js

var logger = function logger(...messages){
    if(process.env.NODE_ENV === 'development'){
        console.log(messages);
    }
}
exports.logger = logger;

现在将此 logger.js 文件导入您的组件。例如我的组件文件是 demo.jsx

import React from 'react';
var logger = require('../logger.js').logger;

class Demo extends React.Component{
    constructor(props){
    }

    render(){
        return(
            <p>Hello i am demo component</p>
        );
    }

    componentDidMount(){
        logger('I am printing only in developmet')
    }
}
export default Demo;

这是我使用 craco 的解决方案。

"@craco/craco": "^6.0.0",
"react-scripts": "4.0.1",

craco.config.js

module.exports = {
  webpack: {
    configure: (webpackConfig) => {
      if (process.env.NODE_ENV === 'production') {
        // remove console in production
        const TerserPlugin = webpackConfig.optimization.minimizer.find((i) => i.constructor.name === 'TerserPlugin');
        if (TerserPlugin) {
          TerserPlugin.options.terserOptions.compress['drop_console'] = true;
        }
      }

      return webpackConfig;
    },
  },
};

这是我使用 craco

的解决方案

安装https://babeljs.io/docs/en/babel-plugin-transform-remove-console/

并更新craco.config.js喜欢

module.exports = {
  plugins: [{ plugin: require('@semantic-ui-react/craco-less') }],
  babel: {
    // ...
  plugins: process.env.NODE_ENV === "production" ? [["transform-remove-console", { "exclude": ["error"] }]] : []
  }
}

我正在使用这种方法来避免弹出 react-scripts

if (process.env.NODE_ENV === 'production') {
  console.log = () => {}
  console.error = () => {}
  console.debug = () => {}
}

index.js

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import './styles/main.scss'

// replace console.* for disable log on production
if (process.env.NODE_ENV === 'production') {
  console.log = () => {}
  console.error = () => {}
  console.debug = () => {}
}

ReactDOM.render(<App />, document.getElementById('root'))

对于那些不想更改他们的 webpack 配置的人来说,这个表达式也可以完成工作并且不需要导入辅助函数:

process.env.NODE_ENV !== "production" && console.log(data);

对于更大或更详细的日志记录应用程序,更改 webpack 配置当然是更优雅的解决方案。

对于 VS Code 用户 我想指出设置 log points 的可能性,如果满足您的需要则完全省略语句。