How to package and optimize react projects

1. View packaging commands

2. Run the package command

My is ` npm run build`   

3. Project packaging and Optimization - Project local Preview

Objective: to be able to preview the packaged project locally


1. Global installation of local service package: npm i -g serve. This package provides the serve command to start the local service
2. Execute the command: serve - S. / build in the project root directory, and start the server in the build directory
3. Access in the browser: http://localhost:3000/ Preview project

4. Project packaging and Optimization - packaging volume analysis

Objective: to be able to analyze the packaged volume of the project

Analysis description: only by analyzing the packaging volume can we know which part of the project is too large and how to optimize it


  1. Install package for analyzing package volume: NPM I source map Explorer

  2. In the scripts tab of package.json, add the command to analyze the package volume

    "scripts": {
      "analyze": "source-map-explorer 'build/static/js/*.js'",

    Package the project: npm run build (if you have already packaged, you can omit this step)

  3. Run analysis command: npm run analyze

5. Project packaging and Optimization - production environment optimization

Objective: the production environment (online) does not need redux debugging tools


  If the environment is a production environment, only the middleware is reserved, otherwise the redux debugging tool is reserved to make logical judgment in the store

import { createStore, applyMiddleware } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunk from 'redux-thunk'
import rootReducers from '@/store/reducers'
let middleware
// If the environment is a production environment, only the middleware is reserved, otherwise the redux debugging tool is reserved
process.env.NODE_ENV === 'production'
  ? (middleware = applyMiddleware(thunk))
  : (middleware = composeWithDevTools(applyMiddleware(thunk)))

export default createStore(rootReducers, middleware)

  After modification, it needs to be repackaged again

6. Project packaging and Optimization - route lazy loading

Objective: to realize the lazy loading of routing, and the introduction method adopts the lazy loading of routing

  Implementation steps

1. In the App component, import the suspend component
2. Inside the Router, use the suspend component to wrap the component content
3. Provide the fallback attribute for the suspend component and specify the loading placeholder content
4. Import the lazy function and modify it to lazy loading mode to import the routing component

Core code:

First level routing App.js

//1. Introduce the tools needed for lazy loading of routes in react
import React, { lazy, Suspense } from 'react'
//Change how routing components are imported
const Login = lazy(() => import('./pages/Login'))
const Layout = lazy(() => import('./pages/Layout'))
//3. Wrap the route with depend. The incoming fallback attribute is the one you need to display when loading the incoming fallback
export default function App () {
  return (
    <Router history={history}>
            <Spin tip="Loading...">
                message="Load medium"
                description="My mother, you don't know your mother anymore"
          <Redirect from="/" exact to="/login" />
          <Route path="/login" component={Login} />
          <AuthRoute path="/home" Component={Layout} />
          <Route path="/home" component={Layout} />
          <Route component={NotFound} />

Secondary routing Layout/index:

const Home = lazy(() => import('../Home/Home.jsx'))

const Article = lazy(() => import('../Article/Article.jsx'))

const Publish = lazy(() => import('../Publish/Publish.jsx'))

  7. Project packaging and Optimization - remove the console

1. Download the package to remove conloso

npm i terser-webpack-plugin@4.2.3

2. The following code is configured in the craco.config.js configuration file

const path = require('path')
const TerserPlugin = require('terser-webpack-plugin')

module.exports = {
  // Identifying the @ symbol
  webpack: {
    alias: {
      '@': path.join(__dirname, 'src')
  // Remove console
  plugins: [
    new TerserPlugin({
      terserOptions: {
        compress: {
          drop_console: process.env.NODE_ENV === 'production'
          // Remove all contents of the console in the production environment

8. Project packaging and Optimization - configure CDN

Objective: to be able to use CDN optimization for third-party packages

1. Don't pack in when packing
2. Introduce external links in public/index.html

Analysis description: modify the webpack configuration through craco to realize CDN optimization

Core code:

In craco.config.js:

const path = require('path')
// HtmlWebpackPlugin
const { whenProd, getPlugin, pluginByName } = require('@craco/craco')
module.exports = {
  webpack: {
    alias: {
      '@': path.join(__dirname, 'src')
    configure: (webpackConfig) => {
      let cdn = {
        js: [],
        css: []
      // Configure webpack
      whenProd(() => {
        // Only in the production environment
        webpackConfig.externals = {
          react: 'React',
          'react-dom': 'ReactDOM',
          redux: 'Redux',

        cdn = {
          js: [
          css: []

      const { isFound, match } = getPlugin(
      if (isFound) {
        // html plugin found
        match.options.cdn = cdn

      return webpackConfig


Keywords: Javascript React

Added by bigrossco on Mon, 22 Nov 2021 09:58:37 +0200