Project packaging and optimization – Project packaging

Goal: To be able to package projects using commands

  1. Open the terminal in the project root directory and enter the package command:npm run build
  2. After the packaging is complete, the packaged content is placed in the Build folder under the project root

Project packaging and optimization – Project local preview

Goal: To be able to preview the packaged project steps locally:

  1. Install local service pack globally:npm i -g serve, the package providesserveCommand to start the local service
  2. Execute the command in the project root directory:serve -s ./buildStart the server in the build directory
  3. Access in a browser:http://localhost:5000/Preview the project

Project packaging and optimization – Package volume analysis

Objective: Be able to analyze project package volume

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

Steps:

  1. Install analysis package volume package: 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'",
    }
    Copy the code
  3. Package the project: NPM Run Build (skip this step if you have already packaged it)

  4. Run the analysis command: NPM run analyze

  5. Analyze the package volume in the diagram from the page that opens in your browser

Core code:

Project packaging and optimization – production environment optimization

Goal: To be able to optimize core code for Redux middleware depending on whether it is for production:

Store/index. In js:

Let middlewares if (process.env.node_env === 'production') { Middlewares = applyMiddleware(thunk)} Else {middlewares = composeWithDevTools(applyMiddleware(thunk))}Copy the code

Project packaging and optimization – route lazy loading

Objective: To be able to lazily load routes to achieve code separation steps:

  1. In the App component, import the Suspense component
  2. Use Suspense components to wrap component content inside the Router
  3. Provide fallback properties for Suspense components to specify loading placeholders
  4. Import the lazy function and change the lazy loading mode to import the routing component

Core code:

App. In js:

import { lazy, Suspense} from 'react' const Login = lazy(() => import('./pages/Login')) const Layout = lazy(() => import('./pages/Layout')) const App = () => { return ( <Router history={history}> <Suspense fallback={ <div style={{ textAlign: 'center', marginTop: 200 }} > loading... </div> } > <div className="app"> <Route exact path="/" render={() => <Redirect to="/home" />}></Route> <Route path="/login" component={Login}></Route> <AuthRoute path="/home" component={Layout}></AuthRoute> </div> </Suspense> </Router> ) } export default AppCopy the code

Pages/Layout/index. In js:

// Use lazy to import components const Home = lazy(() => import('.. /Home')) const Article = lazy(() => import('.. /Article')) const Publish = lazy(() => import('.. /Publish')) // ...Copy the code

Project packaging and optimization – No console

NPM I [email protected]

Exports = {webpack: {const TerserPlugin = require('terser-webpack-plugin') module. Exports = {webpack: { plugins: [ new TerserPlugin({ terserOptions: { compress: { drop_console: Process.env.node_env === 'production' // Remove all contents of console}}})]}}Copy the code

Project packaging and optimization – Configuring CDN

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

Analysis: Through CrACO to modify webpack configuration, so as to achieve CDN optimization

Github.com/facebook/cr…

Core code:

Craco. Config. In 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: Externals = {react: 'react ', 'react-dom': 'ReactDOM', redux: 'Redux', } cdn = { js: [' https://cdn.bootcdn.net/ajax/libs/react/17.0.2/umd/react.production.min.js', 'https://cdn.bootcdn.net/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js', 'https://cdn.bootcdn.net/ajax/libs/redux/4.1.0/redux.min.js'], CSS: [] } }) const { isFound, match } = getPlugin( webpackConfig, PluginByName ('HtmlWebpackPlugin')) if (isFound) {match.options. CDN = CDN} return webpackConfig}}}Copy the code

Public/index. In the HTML:

<! DOCTYPE html><html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="# 000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <! -- manifest.json provides metadata used when your web app is installed on a user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/ -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <! -- Notice the use of %PUBLIC_URL% in the tags above. It will be replaced with the URL of the `public` folder during the build. Only files inside the `public` folder can be referenced from the HTML. Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running `npm run build`. -->
    <title>React App</title>
    <% htmlWebpackPlugin.options.cdn.css.forEach(cdnURL => { %>
      <link rel="stylesheet" href="<%= cdnURL %>"></link>The < %}) % ></head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <! -- This HTML file is a template. If you open it directly in the browser, you will see an empty page. You can add webfonts, meta tags, or analytics to this file. The build step will place the bundled scripts into the <body> tag. To begin the development, run `npm start` or `yarn start`. To create a production bundle, use `npm run build` or `yarn build`. -->
    <% htmlWebpackPlugin.options.cdn.js.forEach(cdnURL => { %>
      <script src="<%= cdnURL %>"></script>The < %}) % ></body>
</html>

Copy the code