react 在creact-react-app中屏蔽console.log、解决moment.js体积过大

安装 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

你可能感兴趣的:(react 在creact-react-app中屏蔽console.log、解决moment.js体积过大)