react 在creact-react-app中屏蔽consol

2021-06-25  本文已影响0人  学生黄哲

安装 craco

$ yarn add @craco/craco
# OR
$ npm install @craco/craco --save

配置文档参考 https://github.com/gsoft-inc/craco/blob/master/packages/craco/README.md#installation

在项目根目录新建craco.config.js文件
my-app
├── node_modules
├── craco.config.js
└── package.json
更新package.json中现有的react-scripts的scripts
"scripts": {
-   "start": "react-scripts start",
+   "start": "craco start",
-   "build": "react-scripts build",
+   "build": "craco build"
-   "test": "react-scripts test",
+   "test": "craco test"
}

使用terser-webpack-plugin

https://github.com/webpack-contrib/terser-webpack-plugin
react-scripts是有配套使用的terser-webpack-plugin的我们不必额外安装,额外安装有可能会产生版本问题
直接使用

在craco.config.js中配置
const TerserPlugin = require('terser-webpack-plugin');
const webpack = require('webpack');
const { NODE_ENV } = process.env;

const Webpack = {
  production: {
    plugins: [
      new TerserPlugin({
        terserOptions: {
          compress: {
            drop_console: true,
            drop_debugger: true,
            pure_funcs: ['console.log'],
          },
        },
      }),
      // 
      // 忽略本地moment.js文件
      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    ],
  },
  development: {},
};

module.exports = {
    ...,
    webpack: Webpack[NODE_ENV],
}

This plugin uses terser to minify your JavaScript.
terser配置文档参考 https://github.com/terser/terser

上一篇下一篇

猜你喜欢

热点阅读