Configure webpack and build a React project from 0

Keywords: Javascript Webpack React sass npm

Let's start with react architecture:
1 Official documents also provide direct download of react packages, but modifying the configuration of webpack is troublesome.

npx create-react-app my-app
cd my-app
npm start

Modifying the webpack configuration requires execution

npm run eject

2. Build a project by yourself and configure webpack - it may not be very good to record learning stages and summaries. Just take a look and focus on recording the second way.

Manage packages through yarn
 
  1. Download yarn

    yarn official website link Installation steps are available

  2. Under the project directory, execute yarn init

    Our package.json file will appear

  3. Install webpack

    yarn add webpack --dev

  4. New webpack.config.js file,

    Examples posted on the official website:

           const path = require('path');
           module.exports = {
             entry: './src/app.js',
             output: {
               path: path.resolve(__dirname, 'dist'),
               filename: 'app.js'
             }
           };

    Executing webpack from the command line will find the dist directory

    Note: If something goes wrong during the installation of yarn, try to switch yarn to Taobao image and download it again. I had problems during the installation process, so that's all right.
    yarn config set registry 'https://registry.npm.taobao.org'

  5. Install html-webpack-plugin

    yarn add html-webpack-plugin --dev
    

Documents use link addresses
Modify webpack.config.js to package HTML files using html-webpack-plugin according to document operations
If you execute the webpack command again, you will find an additional index.html under the dist folder.
Set the template template for html-webpack-plugin, create index.html in src, and set HTML content

  
    const path = require('path');
    var HtmlWebpackPlugin = require('html-webpack-plugin');
    module.exports = {
      entry: './src/app.js',
      output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'app.js'
      },
      plugins: [new HtmlWebpackPlugin(
        {
            template:'./src/index.html'
        }
      )]
    };

Now the index.html under the dist document is the template of index.html under the current src

  1. Install babel

    yarn add babel-loader @babel/core @babel/preset-env

See the document address for details. Write some ES6 grammar in src/app.js, execute the webpack command again, and dist/app.js is converted.

  1. Install react transformation babel-preset-react

    yarn add babel-preset-react --dev

    Modify webpack.config.js

       const path = require('path');
       var HtmlWebpackPlugin = require('html-webpack-plugin');
       module.exports = {
         entry: './src/app.jsx'
           path: path.resolve(__dirname, 'dist'),
           filename: 'app.js'
         },
         plugins: [new HtmlWebpackPlugin(
           {
               template:'./src/index.html'
           }
         )],
         module: {
           rules: [
             {
               test: /\.m?jsx$/,
               exclude: /(node_modules|bower_components)/,
               use: {
                 loader: 'babel-loader',
                 options: {
                   presets: ['@babel/preset-env','react']
                 }
               }
             }
           ]
         }
       };
    
  2. Install react
    yarn add react react-dom
    react adds operation address details
    Modify src/app.js to app.jsx

       import React from 'react';
       import ReactDOM from 'react-dom';
    
       ReactDOM.render(
         <h1>Hello, world!</h1>,
         document.getElementById('app')
       );

    Re-execute webpack for packaging
    If Error: Plugin/Preset files are not allowed to export objects, only functions.

This means that the versions of Babel are inconsistent. I'm here because "babel-preset-react": "^6.24.1" is installed by default in version 6, and other babels are installed in version 7, so they are upgraded to version 7 or downgraded to version 6.

yarn add babel-preset-react@7.0.0 --dev

So when you pack it, you can open dist/index.html, and we see hello, world! You said you compiled react successfully.

  1. Install style-loader

    yarn add css-loader style-loader --dev
    Installation Address Operation Details
    Add in the rules of webpack.config.js

     {
       test: /\.css$/,
       use: ['style-loader', 'css-loader'],
     },

    Create a new file index.css under src and modify any style

       h1{
           color:#F00;
       }

    Introducing app.jsx

       import './index.css'

    Execute webpack packaging again and refresh dist/index.html

  2. Install the ExtractText Web pack Plugin plug-in to separate css into separate files

       yarn add extract-text-webpack-plugin --dev

    Link Address on Official Website

       const path = require('path');
       var HtmlWebpackPlugin = require('html-webpack-plugin');
       const ExtractTextPlugin = require("extract-text-webpack-plugin");
       module.exports = {
           entry: './src/app.jsx',
           output: {
               path: path.resolve(__dirname, 'dist'),
               filename: 'app.js'
           },
           module: {
               rules: [
               {
                   test: /\.m?jsx$/,
                   exclude: /(node_modules|bower_components)/,
                   use: {
                   loader: 'babel-loader',
                   options: {
                       presets: ['@babel/preset-env','react']
                   }
                   }
               },
               {
                   test: /\.css$/,
                   use: ExtractTextPlugin.extract({
                       fallback: "style-loader",
                       use: "css-loader"
                   })
               },
               ]
           },
           plugins: [
               new HtmlWebpackPlugin(
                   {
                       template:'./src/index.html'
                   }
               ),
               new ExtractTextPlugin("index.css"),
           ],
       };

    The webpack.config.js configuration is as follows
    Executing webpack again will add an index.css to the dist directory.
    Note: Packing encountered a Tapable. plugin is deprecated. Use new API on. hooks instead error because the current version of extract-text-webpack-plugin does not support webpack4
    Execution: yarn add extract-text-webpack-plugin@next--dev

  3. Install sass-loader

       yarn add sass-loader --dev

    Adding rules to webpack.config.js

       {
           test: /\.scss$/,
           use: ExtractTextPlugin.extract({
               fallback: 'style-loader',
               use: ['css-loader', 'sass-loader']
           })
       }

    Create a new index.scss file

       body{
           background: #ccc;
           #app{
               font-size: 22px;
           }
       }

    Error Cannot find module'node-sass'when executing webpack
    View Document Links
    Need to install node-sass

       yarn add node-sass --dev

    Packing, looking at index.html, you can see that the style has been applied to

  4. Install url-loader to process picture links

       yarn add url-loader file-loader --dev

    Official website address
    Add in rules:

       {
           test: /\.(png|jpg|gif)$/i,
           use: [
             {
               loader: 'url-loader',
               options: {
                 limit: 8192
               }
             }
           ]
       }

    Pictures are introduced into the project and packaged, so that the image resources are packaged and parsed into the

  5. Add parsing font rule

      {
           test: /\.(eot|svg|ttf|woff|woff2|otf)$/i,
           use: [
               {
                 loader: 'url-loader',
                 options: {
                   limit: 8192,
                   name:'resource/[name].[ext]'
                 }
               }
           ]
       },
    
  6. Add webpack-dev-server

       yarn add webpack-dev-server --dev

    Modify package.json add
    "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "watch": "webpack --watch",
    "start": "webpack-dev-server --open",
    "build": "webpack-cli"
    }
    Execute yarn run start startup project

    yarn run build package project

    Finally, we attach the webpack.config.js that has been modified so far.

           const path = require('path');
           const webpack = require('webpack');
           var HtmlWebpackPlugin = require('html-webpack-plugin');
           const ExtractTextPlugin = require("extract-text-webpack-plugin");
           module.exports = {
               entry: './src/app.jsx',
               output: {
                   path: path.resolve(__dirname, 'dist'),
                   filename: './js/[name].[hash].js',
                   chunkFilename: './js/[name].[hash].js',
               },
               devServer: {
                   port: 8080,
                   proxy: {
                       '/expo': {
                           target: 'https://xxx',
                           changeOrigin: true,
                           pathRewrite: {
                               '/expo': '/expo',
                           },
                           secure: false,
                       },
                   },
                   hot:true
               },
               module: {
                   rules: [
                   {
                       test: /\.m?jsx$/,
                       exclude: /(node_modules|bower_components)/,
                       use: {
                       loader: 'babel-loader',
                       options: {
                           presets: ['@babel/preset-env','react']
                       }
                       }
                   },
                   {
                       test: /\.css$/,
                       use: ExtractTextPlugin.extract({
                           fallback: "style-loader",
                           use: "css-loader"
                       })
                   },
                   {
                       test: /\.scss$/,
                       use: ExtractTextPlugin.extract({
                           fallback: 'style-loader',
                           use: ['css-loader', 'sass-loader']
                       })
                   },
                   {
                       test: /\.(png|jpg|gif|ico|jpeg)$/i,
                       use: [
                         {
                           loader: 'url-loader',
                           options: {
                               limit: 8192,
                               name: "[name].[ext]",
                               publicPath: "../images/",
                               outputPath: "images/"
                           }
                         }
                       ]
                   },
                   {
                       test: /\.(eot|svg|ttf|woff|woff2|otf)$/i,
                       use: [{
                           loader: "file-loader",
                           options: {
                             name: "[name].[ext]",
                             publicPath: "../fonts/",
                             outputPath: "fonts/"
                           }
                       }]
                   },
                   ]
               },
               plugins: [
                   new HtmlWebpackPlugin(
                       {
                           template:'./src/index.html'
                       }
                   ),
                   new ExtractTextPlugin("css/[name].css"),
               ],
               optimization:{
                   splitChunks:{
                       name:'common',
                       filename:'js/base.js'
                   }
               }
           };
    

Posted by y4m4 on Sat, 04 May 2019 14:20:39 -0700