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

How to use JavaScript to implement sorting algorithms

Table of contents Bubble Sort Selection Sort Inse...

Solve the problem of docker container exiting immediately after starting

Recently I was looking at how Docker allows conta...

MySQL 8.x msi version installation tutorial with pictures and text

1. Download MySQL Official website download addre...

Writing and understanding of arrow functions and this in JS

Table of contents Preface 1. How to write functio...

How to implement MySQL bidirectional backup

MySQL bidirectional backup is also called master-...

How to solve the mysql insert garbled problem

Problem description: When inserting Chinese chara...

A simple way to achieve scrolling effect with HTML tag marquee (must read)

The automatic scrolling effect of the page can be...

Sample code for implementing Alipay sandbox payment with Vue+SpringBoot

First, download a series of things from the Alipa...

Reduce memory and CPU usage by optimizing web pages

Some web pages may not look large but may be very ...

Vue realizes picture switching effect

This article example shares the specific code of ...

Docker installation and configuration steps for MySQL

Table of contents Preface environment Install Cre...

Docker installs Elasticsearch7.6 cluster and sets password

Starting from Elasticsearch 6.8, free users are a...

Avoid abusing this to read data in data in Vue

Table of contents Preface 1. The process of using...

Why is it not recommended to use index as key in react?

1. Compare the old virtual DOM with the new virtu...