How to modify create-react-app's configuration without using eject

How to modify create-react-app's configuration without using eject

1. Why is eject not recommended?

1. What changes have occurred after executing eject?

The create-react-app framework itself encapsulates the relevant configurations of webpack and babel in react-scripts. After executing yarneject, the configurations of webpack, babel, etc. will be exposed in the config directory. At the same time, new command files will be updated in the scripts directory, and the scripts commands in the package.json file will be updated synchronously.

2. What problems does executing eject bring?

First of all, the execution of eject is irreversible, and complex configurations such as webpack are handed over from the framework itself to the user for maintenance.

Secondly, during version iteration, if dependencies such as react, react-scripts, eslint, tsconfig, etc. are updated, version dependency problems may occur. Even if we fix them according to the error message, the project still cannot run.

Therefore, we generally do not recommend using yarneject to expose the configuration of the create-react-app framework.

2. How to solve the needs

In actual development, we still need to update the configuration of webpack and babel, for example:

  • On-demand loading of antd;
  • Configure the css preprocessor - less;
  • Set aliases and externals;
  • Production environment packaging-remove console.log and debugger;
  • Packaging result optimization analysis;
  • Add progress bar prompt during packaging;

High energy warning ahead~

yarn add react-app-rewired customize-c to complete the configuration extension~

Here is the key point, remember to take the test~

We divide it into several steps to achieve them one by one:

Download and install dependencies

yarn add react-app-rewired customize-cra -D

The versions currently used are react-app-rewired@^2.1.8、customize-cra@^1.0.0

Commands for configuring package.json

"scripts": {
- "start": "react-scripts start",
+ "start": "react-app-rewired start",
- "build": "react-scripts build",
+ "build": "react-app-rewired build",
}

Configure the config-overrides.js file in the root directory

module.exports = {}

After completing the basic configuration, we perform detailed configuration in config-overrides.js to solve our above requirements.

1. On-demand loading of antd

Install dependencies:

yarn add antd -D

Configuration

cosnt { override, fixBabelImports } = require('customize-cra');
module.exports = override(
	fixBabelImports
  	"import",
    {
      "libraryName": "antd",
      "libraryDirectory": "es",
      "style": "css"
    }
  )

2. Configure the CSS preprocessor - less

Why only less is emphasized here? Because create-react-app has built-in sass/scss preprocessors, and you only need to install related dependencies when using it (when running, just install the missing packages according to the prompts).

yarn add sass -D

Next, let's look at how less supports

Installation dependencies:

yarn add less [email protected] -D

Note that the version of less-loader here is [email protected]. If it is the latest version, there will be problems when configuring it with the above react-app-rewired and customize-cra versions, so the lower version is used.

The latest version of less-loader is actually designed to be used with [email protected].

Configuration

const { override, addLessLoader } = require('customize-cra');
module.exports = override(
addLessLoader({
// You can add other less configurations here lessOptions: {
   	//Configure according to your needs~
    }
})
);

3. Set aliases and externals;

const { override, addWebpackAlias ​​} = require('customize-cra');
const path = require('path');
module.exports = override(
  // alias
addWebpackAlias({
    // When loading a module, you can use the "@" symbol for abbreviation~
    '@': path.resolve(__dirname, './src/')
  }),
  // externals
  addWebpackExternals({
    // Note the corresponding remote file address of jQuery introduced in public/index.html "jQuery": "jQuery"
  })

4. Production environment packaging - remove console.log and debugger;

Install Dependencies

yarnadduglifyjs-webpack-plugin-D

Configuration

const { override, addWebpackPlugin } = require('customize-cra');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = override(
	// Note that the plugin is started in the production environment
	process.env.NODE_ENV === 'production' && addWebpackPlugin(
  	new UglifyJsPlugin({
  		// Enable package cache cache: true,
  		// Enable multi-threaded packaging parallel: true,
  		uglifyOptions: {
  			// Delete warnings warnings: false,
  			//Compression compress: {
  				// Remove the console
  				drop_console: true,
  				// Remove the debugger
  				drop_debugger: true
  			}
  		}
  	})
  )

5. Packaging result optimization analysis;

Install Dependencies

yarn add webpack-bundle-analyzer cross-env -D

cross-env is used to configure environment variables

Configuration

// package.json file "scripts": { "build:analyzer": "cross-env ANALYZER=true react-app-rewired build" }

// config-overrides.js
const { override, addWebpackPlugin } = require('customize-cra');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
module.exports = override(
  // Determine the value of the environment variable ANALYZER parameter process.env.ANALYZER && addWebpackPlugin(new BundleAnalyzerPlugin())
)

6. Add progress bar prompt during packaging;

Install Dependencies

yarnaddprogress-bar-webpack-plugin-D
const { override, addWebpackPlugin } = require('customize-cra');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
module.exports = override(
	addWebpackPlugin(new ProgressBarPlugin())
)

The above is the configuration we implemented several requirements. Let's take a look at the complete config-overrides.js file.

// config-overrides.js
cosnt { override, fixBabelImports, addWebpackPlugin, addLessLoader, addWebpackAlias, addWebpackExternals } = require('customize-cra');
const path = require('path');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
module.exports = override(
	fixBabelImports
  	"import",
    {
			"libraryName": "antd",
      "libraryDirectory": "es",
      "style": "css"
    }
  ),
  addLessLoader({
		// You can add other less configurations here lessOptions: {
   		//Configure according to your needs~
    }
	}),
  // alias
	addWebpackAlias({
    // When loading a module, you can use the "@" symbol for abbreviation~
    '@': path.resolve(__dirname, './src/')
  }),
  // externals
  addWebpackExternals({
    // Note the corresponding remote file address of jQuery introduced in public/index.html "jQuery": "jQuery"
  }),
  // Note that the plugin is started in the production environment
	process.env.NODE_ENV === 'production' && addWebpackPlugin(
  	new UglifyJsPlugin({
  		// Enable package cache cache: true,
  		// Enable multi-threaded packaging parallel: true,
  		uglifyOptions: {
  			// Delete warnings warnings: false,
  			//Compression compress: {
  				// Remove the console
  				drop_console: true,
  				// Remove the debugger
  				drop_debugger: true
  			}
  		}
  	})
  ),
  // Determine the value of the ANALYZER parameter of the environment variable process.env.ANALYZER && addWebpackPlugin(new BundleAnalyzerPlugin()),
  addWebpackPlugin(new ProgressBarPlugin())
)

This is the end of this article on how to modify the configuration of create-react-app without using eject. For more information about modifying the configuration of create-react-app, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Solution to the error reported when creating a project with npx create-react-app xxx
  • Solution to create-react-app installation error
  • Detailed explanation of create-react-app, the best scaffolding for developing react applications
  • React creates a project based on create-react-app
  • How to modify the port number password in the configuration file in redis

<<:  Analyzing the four transaction isolation levels in MySQL through examples

>>:  How to configure nginx+php+mysql in docker

Recommend

Python writes output to csv operation

As shown below: def test_write(self): fields=[] f...

Solution to the problem of slow docker pull image speed

Currently, Docker has an official mirror for Chin...

Vue.js implements music player

This article shares the specific code of Vue.js t...

Introduction to Sublime Text 2, a web front-end tool

Sublime Text 2 is a lightweight, simple, efficien...

How to create a view in MySQL

Basic syntax You can create a view using the CREA...

Implementation example of video player based on Vue

When the existing video player cannot meet the ne...

jQuery implements article collapse and expansion functions

This article example shares the specific code of ...

Implementation of remote Linux development using vscode

Say goodbye to the past Before vscode had remote ...

The difference between name and value in input tag

type is the control used for input and output in t...

A brief discussion on the VUE uni-app life cycle

Table of contents 1. Application Lifecycle 2. Pag...

Optimized record of using IN data volume in Mysql

The MySQL version number is 5.7.28. Table A has 3...