current position:Home>Xiaobai learns to build react infrastructure

Xiaobai learns to build react infrastructure

2021-08-27 10:27:46 Mice can fly

This document is based on webpack5、node10 To build , Make sure you have installed node development environment

1、 initialization react project

New on desktop react-demo, Running at the same time npm init -y, At this time, you can see that there are... In the root directory of the project package.json This file , This file is similar to maven Of pom.xml, It is used to manage all dependencies and other basic information in the front-end project .

2、 install webpack、webpack-cli、webpack-dev-server

npm i webpack webpack-cli webpack-dev-server -D
 Copy code 

These three dependencies are based on webpack Development 、 Necessary dependencies for packaging . After installation , New in the root directory build Catalog , I use it here vue-cli2 Directory structure of . At the same time build New under the directory webpack.base.config.js file .webpack.base.config.js Is as follows :

const path = require('path');
const HtmlWebPackPlugin = require("html-webpack-plugin");

module.export = (env) => {
    return {
        entry: {
            "app": path.resolve(__dirname, "../src/index.js");
        },
        output: {
            path: path.resolve(__dirname, '../dist')
        },
        module: {
            rules: [{
                test: /\.(j|t)s$/,
                use: [
                    {
                        loader: "babel-loader"
                    }
                ]
            }, {
                test: /\.(sc|c)ss$/,
                use: [
                    "loader": "style-loader",
                    "loader": "css-loader",
                    "loader": "postcss-loader",
                    "loader": "scss-loader"
                ]
            }]
        },
        plugins: [
            new HtmlWebPackPlugin({
                template: path.resolve(__dirname, "../index.html"),
                filename: path.resolve(__dirname, "../dist/index.html")
            })
        ]
    }
}
 Copy code 

New in the root directory index.html, The contents are as follows :

<!DOCTYPE html>
<html>
<head>
    <title>index</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
</head>
<body>
    <div id="root"></div>
</body>
</html>
 Copy code 

stay webpack.base.config.js In file , We see that the entry file is src In the catalog index.js file , So create a new one under the root directory src Catalog , stay src New under the directory index.js file , The contents of the document are as follows :

import App from './App';
import ReactDom from 'react-dom';
import React from 'react';

ReactDom.render(
  <App />,
  document.getElementById('root'));
 Copy code 

New in the root directory App.js, It's a page . The contents are as follows :

import React from 'react';

class App extends React.Component {
    render() {
        return (<div>APP  page </div>)
    }
}
 Copy code 

After writing the basic contents of the above items , I found that many key dependencies were not installed , The project can't run at this time .

3、 install react、react-dom

npm i react react-dom -S
 Copy code 

react Official documents

react-dom Official documents

4、 install html-webpack-plugin、@babel/core、babel-loader、@babel/preset-env、@babel/preset-react、style-loader、css-loader、autoprefixer、node-sass、sass-loader、postcss-normalize、postcss-loader

I won't introduce these plug-ins one by one , You can baidu if you don't know .postcss Need configuration , New in the root directory postcss.config.js, The contents are as follows :

const postcssNormalize = require('postcss-normalize');

module.exports = {
  plugins: [
    [
      "postcss-preset-env",
      {
        autoprefixer: {
          flexbox: "no-2009",
        },
        stage: 3,
      }
    ],
    postcssNormalize(),
    require('autoprefixer') ({
      overrideBrowserslist: ['last 2 version', '>1%', 'ios 7']
    })
  ],
};
 Copy code 

New in the root directory babel.config.js, The contents are as follows :

{
    "presets": ["@babel/preset-env", "@babel/preset-react"]
}
 Copy code 

stay package.json Add run script to :

"dev": "webpack serve --progress --config ./build/webpack.base.config.js",
"build": "webpack --progress --config ./build/webpack.base.config.js"
 Copy code 

Now you can run the project

5、 Profile separation

In actual development, we don't want to mix the production environment configuration with the development environment configuration , So we need to separate the environment . Installing a plug-in webpack-merge, At the same time build New under the directory webpack.dev.config.js、webpack.prod.config.js, The contents are as follows :

const { merge } = require("webpack-merge");
const baseConfig = require("./webpack.base.config");

module.exports = (env) => {
    return merge(baseConfig, {
        mode: "development",
        output: {
            filename: "js/index.bundle[hash*7].js"
        },
        devServer: {
            host: '0.0.0.0',
            port: 8080,
            hot: true
        },
        optimization: {
            moduleIds: "deterministic",
        },
        cache: {
            type: 'filesystem',
            //  Optional configuration 
            buildDependencies: {
                config: [__filename], //  When building dependent config file ( adopt  require  rely on ) When the content changes , Cache invalidation 
            },
            name: 'development-cache',
        }
    })
}
 Copy code 
const path = require("path");
const { merge } = require('webpack-merge');
const baseConfig = require('./webpack.base.config.js');
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const { WebpackManifestPlugin } = require('webpack-manifest-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const TerserPlugin = require('terser-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');

module.exports = env => {
  return merge(baseConfig, {
    mode: 'production',
    output: {
      filename: "js/[name].bundle[contenthash][hash*7].js"
    },
    plugins: [
      //  Empty the packaging directory before packaging 
      new CleanWebpackPlugin(),
      //  Package analysis 
      new BundleAnalyzerPlugin(),
      //  Generate  manifest.json
      new WebpackManifestPlugin(),
      //  take  css  from  js  In the separation of 
      new MiniCssExtractPlugin({
        filename: "css/[name].[contenthash][hash*7].css",
      }),
    ],
    optimization: {
      minimize: true,
      minimizer: [
        new TerserPlugin({
          parallel: true,
        }),
        new CssMinimizerPlugin(),
      ],
      splitChunks: {
        chunks: 'async'
      },
    },
  });
}
 Copy code 

modify webpack.base.config.js:

const path = require("path");
const HtmlWebPackPlugin = require("html-webpack-plugin");

module.exports = {
    entry: path.resolve(__dirname, '../src/index.js'),
    output: {
        path: path.resolve(__dirname, '../dist')
    },
    resolve: {
        extensions: [".js"],
    },
    module: {
        rules: [
            {
                test: /\.js?$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            },
            {
                test: /\.(c|sc)ss?$/,
                exclude: /node_modules/,
                use: {
                    loader: "style-loader",
                    loader: "css-loader",
                    loader: "postcss-loader",
                    loader: "sass-loader"
                }
            },
            {
                test: /\.(jpe?g|png|gif|svg|woff|woff2|eot|ttf|otf)$/i,
                type: "asset/resource",
            },
        ]
    },
    plugins: [
        new HtmlWebPackPlugin({
            template: path.resolve(__dirname, "../index.html"),
            filename: path.resolve(__dirname, "../dist/index.html")
        })
    ]
}
 Copy code 

At the end

Attach the final structure of the project :

.react-demo
│  .babelrc
│  dir.md
│  index.html
│  package-lock.json
│  package.json
│  postcss.config.js
│  
├─build
│      webpack.base.config.js
│      webpack.dev.config.js
│      webpack.prod.config.js
│        
└─src
    │  App.js
    │  index.js
    │  
    └─redux
        │  index.js
        │  
        ├─actions
        │      index.js
        │      
        ├─reducers
        │      index.js
        │      
        └─sagas
                index.js
                
 Copy code 

copyright notice
author[Mice can fly],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827102742623S.html

Random recommended