简体   繁体   English

如何在使用 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?

this is what i did.这就是我所做的。 create a helper folder with a file called ConsoleHelper.js使用名为ConsoleHelper.js的文件创建一个helper文件夹

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

export default ConsoleHelper;

instead of console.log(data) do ConsoleHelper(data) ;而不是console.log(data)ConsoleHelper(data)

hope this helps.希望这可以帮助。 i console log alot :)我控制台日志很多:)

This is my solution using craco .这是我使用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;
    },
  },
};

The simple solution to the question is to help others who are facing the same issue.这个问题的简单解决方案是帮助面临同样问题的其他人。

Ref: https://stackoverflow.com/a/41041580/3574669参考: https : //stackoverflow.com/a/41041580/3574669

The suggestion in the reference, it needs to do a change in the file "webpack.config.js".参考中的建议,它需要在文件“webpack.config.js”中进行更改。 The create-react-app uses the webpack and the config file internally but it is not possible to add webpack.config.js in my application root for applying the change. create-react-app 在内部使用 webpack 和配置文件,但无法在我的应用程序根目录中添加 webpack.config.js 以应用更改。 This would need to leave the create-react-app setup and build own setup for webpack and configuration.这将需要离开 create-react-app 设置并为 webpack 和配置构建自己的设置。 It does not find easy for me after exploring a lot and writing sample code.经过大量探索和编写示例代码后,我觉得这并不容易。

Since I am very much satisfied with create-react-app so also don't want to keep aside its benefits.因为我对 create-react-app 非常满意,所以也不想搁置它的好处。

Finally, I did a simple change in the node_modules/react-scripts/config/webpack.config.js by adding a line drop_console: true, as mentioned in the reference.最后,我通过添加一行drop_console: true,node_modules/react-scripts/config/webpack.config.js做了一个简单的更改drop_console: true,如参考文献中所述。 The suggested code in the reference is as below,参考中的建议代码如下,

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 //
          },
        },
      }),
    ],
  },
};

This works fine to me and there is no console log in my production build application by the simple change.这对我来说很好用,并且通过简单的更改,我的生产构建应用程序中没有控制台日志。

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

Note: This new line will be cleaned whenever you reinstall "react-scripts" later.注意:当您稍后重新安装“react-scripts”时,将清除此新行。 So it would need to again do the same change in such an event.因此,它需要在此类事件中再次进行相同的更改。

IMPORTANT: Don't use this approach if using CI/CD重要提示:如果使用 CI/CD,请勿使用此方法

The simple way is to create a new file in root named logger.js简单的方法是在 root 中创建一个名为logger.js的新文件

In logger.js在 logger.js 中

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

Now import this logger.js file to your components.现在将此 logger.js 文件导入到您的组件中。 For example my component file is demo.jsx例如我的组件文件是 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;

This is my solution using craco这是我使用craco解决方案

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

and update craco.config.js like并更新 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"] }]] : []
  }
}

I am using this approach to avoid ejecting react-scripts我正在使用这种方法来避免弹出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'))

For those not wanting to make changes to their webpack config, this expression does the job as well and without the need of importing a helper function:对于那些不想更改他们的 webpack 配置的人,这个表达式也可以完成这项工作,并且不需要导入辅助函数:

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

For larger or more verbosely logging applications, changing the webpack config is a more elegant solution of course.对于更大或更冗长的日志应用程序,更改 webpack 配置当然是更优雅的解决方案。

For VS Code users i want point out the possibility to set log points and omit the statement altogether if that serves your need.对于 VS Code 用户,我想指出设置 日志点的可能性,如果满足您的需要,则完全省略该语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在使用“create-react-app”创建的 reactjs 的生产过程中删除 console.log - how to remove console.log during production in reactjs created with `create-react-app` 如何删除 React App 符号和名称或“使用 create-react-app 创建的网站”? - How can I remove the React App symbol and name or the “Website created using create-react-app”? 在生产构建中创建 React-App 代理 - Create-React-App Proxy in Production Build 如何从 Create-React-App 生产构建中排除 React Refresh? - How can I exclude React Refresh from the Create-React-App production build? 为什么我的 create-react-app console.log 两次? - Why does my create-react-app console.log twice? "在反应生产构建中删除控制台日志语句?" - Remove console log statements in react production build? 在生产环境中使用带有Express的Create-React-App - Using Create-React-App with Express in production 将使用 create-react-app 创建的 React 应用程序集成到外部应用程序中 - Integrate React app created with create-react-app into an external application 如何使用 create-react-app 配置创建和运行应用程序的开发版本 - How to create and run a development build of an application using create-react-app configuration 如何从链接中删除“使用 create-react-app 创建”? - How to delete "created using create-react-app" from links?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM