First, throw the question

Many students who are new to the create-React-app framework will be wondering how to change the create-React-app configuration without performing eject. Today Hu Ge will take you to look at this problem ~

Why eject is not recommended

1. What happens when you execute eject?

Create-react-app encapsulates webpack and Babel configurations in react-scripts. After yarn eject is executed, webpack and Babel configurations are exposed in the config directory. At the same time, new command files will be updated in the scripts directory, and the scripts command will be updated synchronously in the package.json file.

2. What are the problems with implementing eject?

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

Second, if you update dependencies like React, React-scripts, ESLint, tsconfig, etc., during version iteration, it may cause version-dependent problems, and the project will still not run even after we fix it with the error message.

It is generally not recommended to expose the create-React-app framework configuration using YARN eject.

Three, how to solve the need

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

  • Antd loading on demand;

  • Configure the CSS preprocessor less.

  • Set alias and externals.

  • Production environment packaging – remove console.log, debugger;

  • Optimization analysis of packaging results;

  • [Fixed] Added progress bar prompt for packaging

High energy warning ahead ~

React-app-rewired and customize-cra are used to extend the configuration

Here are the key points, remember to test yo ~

We have several steps to implement each one:

  1. Download and install dependencies

    yarn add react-app-rewired customize-cra -D
    Copy the code

    The version hu now uses is react-app-rewired@^2.1.8, customize-cra@^1.0.0

  2. The command to configure package.json

    "scripts": {
    -   "start": "react-scripts start".+		"start": "react-app-rewired start".-   "build": "react-scripts build".+   "build": "react-app-rewired build",}Copy the code
  3. Configure the config-overrides. Js file in the root directory

    module.exports = {}
    Copy the code

After the basic configuration was completed, detailed configuration was carried out in config-overrides. Js to solve the above requirements.

1. antdLoad on demand

Install dependencies:

yarn add antd -D
Copy the code

configuration

cosnt { override, fixBabelImports } = require('customize-cra');

module.exports = override(
	fixBabelImports(
  	"import",
    {
			"libraryName": "antd"."libraryDirectory": "es"."style": "css"}))Copy the code

2. Configure the CSS preprocessor less

Create-react-app has a built-in SASS/SCSS preprocessor, so you only need to install the dependencies when you use create-React-app.

yarn add sass -D
Copy the code

How do we support less

Install dependencies:

yarn add less less-loader@7.3. 0 -D
Copy the code

Note that the version of less-loader here [email protected], if the latest version is configured with the react-app-Rewired and customize-cra versions above, there are problems, so the lower version is used.

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

configuration

const { override, addLessLoader } = require('customize-cra');

module.exports = override(
	addLessLoader({
		// Other configurations for less can be added here
		lessOptions: {
   		// Configure it as required}}));Copy the code

3. Set alias and externals.

const { override, addWebpackAlias } = require('customize-cra');
const path = require('path');

module.exports = override(
  // alias
	addWebpackAlias({
    // When loading modules, you can use the "@" symbol to abbreviate ~
    The '@': path.resolve(__dirname, './src/')}),// externals
  addWebpackExternals({
    // Note the corresponding remote file address introduced in jquery in public/index.html
    "jQuery": "jQuery"}))Copy the code

4. Package the production environment and remove console.log and debugger.

Install dependencies

yarn add uglifyjs-webpack-plugin -D
Copy the code

configuration

const { override, addWebpackPlugin } = require('customize-cra');
const  UglifyJsPlugin = require('uglifyjs-webpack-plugin');

module.exports = override(
	// Note that the production environment starts the plugin
	process.env.NODE_ENV === 'production' && addWebpackPlugin(
  	new UglifyJsPlugin({
  		// Enable packaging cache
  		cache: true.// Enable multi-threaded packaging
  		parallel: true.uglifyOptions: {
  			// Delete the warning
  			warnings: false./ / compression
  			compress: {
  				/ / remove the console
  				drop_console: true./ / remove the debugger
  				drop_debugger: true}}}))Copy the code

5. Optimization analysis of packaging results;

Install dependencies

yarn add webpack-bundle-analyzer cross-env -D
Copy the code

Cross-env is used to configure environment variables

configuration

// package.json file "scripts": {"build: Analyzer ": "cross-env Analyzer =true react-app-rewired build"}Copy the code
// config-overrides.js
const { override, addWebpackPlugin } = require('customize-cra');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

module.exports = override(
  // Determines the value of the environment variable ANALYZER parameter
	process.env.ANALYZER && addWebpackPlugin(new BundleAnalyzerPlugin())
)
Copy the code

6. Add progress bar prompt for packaging;

Install dependencies

yarn add progress-bar-webpack-plugin -D
Copy the code
const { override, addWebpackPlugin } = require('customize-cra');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');

module.exports = override(
	addWebpackPlugin(new ProgressBarPlugin())
)
Copy the code

This is the configuration we used to implement several requirements. Let’s 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({
		// Other configurations for less can be added here
		lessOptions: {
   		// Configure it as required}}),// alias
	addWebpackAlias({
    // When loading modules, you can use the "@" symbol to abbreviate ~
    The '@': path.resolve(__dirname, './src/')}),// externals
  addWebpackExternals({
    // Note the corresponding remote file address introduced in jquery in public/index.html
    "jQuery": "jQuery"
  }),
  // Note that the production environment starts the plugin
	process.env.NODE_ENV === 'production' && addWebpackPlugin(
  	new UglifyJsPlugin({
  		// Enable packaging cache
  		cache: true.// Enable multi-threaded packaging
  		parallel: true.uglifyOptions: {
  			// Delete the warning
  			warnings: false./ / compression
  			compress: {
  				/ / remove the console
  				drop_console: true./ / remove the debugger
  				drop_debugger: true}}})),// Determines the value of the environment variable ANALYZER parameter
	process.env.ANALYZER && addWebpackPlugin(new BundleAnalyzerPlugin()),
  addWebpackPlugin(new ProgressBarPlugin())
)
Copy the code

Afterword.

The above is brother Hu to share the content today, like partners remember to like, collect ah, pay attention to Brother Hu has words, learning front end don’t get lost, welcome a lot of messages exchange…

Hu Ge has words, focus on the field of front-end technology, share front-end system architecture, framework implementation principle, the latest and most efficient technology practice!