Install and use WebPack

1. Initialize the project

mkdir react-redux && cd react-redux
npm init -y
Copy the code

2. Install webpack

npm i webpack -D
Copy the code

NPM i-d is short for NPM install –save-dev. It is a package that installs the module and saves it in devDependencies of package.json, mainly in the development environment. If you use the WebPack 4+ version, you also need to install the CLI.

npm install -D webpack webpack-cli
Copy the code

3. Create a new project structure

  react-redux
  |- package.json
+ |- /dist
+   |- index.html
  |- /src
    |- index.js
Copy the code

index.html


      
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="root"></div>
<script src="bundle.js"></script>
</body>
</html>
Copy the code

index.js

document.querySelector('#root').innerHTML = 'webpack use';
Copy the code

Packaging in a non-global installation.

node_modules\.bin\webpack src\index.js --output dist\bundle.js --mode development
Copy the code

Open the HTML in the Dist directory to show webpack use

Configuration webpack

1. Use the configuration file

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

Node_modules \.bin\webpack –mode production 2.NPM Scripts add an NPM script to package.json: “Build “: “webpack –mode production” Run NPM run build

Build the local server using Webpack

Webpack-dev-server provides a simple Web server that can be reloaded in real time. 1. Install NPM I -d webpack-dev-server to modify the webpack.config.js configuration file

const path=require('path');
module.exports={
    entry:'./src/index.js',
    output:{
        filename:'bundle.js',
        path:path.resolve(__dirname,'dist'}, // The following is the new configuration devServer:{contentBase:"./dist",// The directory where the page is loaded by the local serverhistoryApiFallback: true,// do not jump to inline:truePort :3000, open:true,// Automatically open browser}};Copy the code

Run webpack-dev-server –progress, open the browser localhost:3000, and the modified code will be displayed in real time. To add scripts, run NPM start to automatically open http://localhost:8080/

"start": "webpack-dev-server --open --mode development" 
Copy the code

After starting webpack-dev-server, the compiled files are not seen in the target folder, and the real-time compiled files are saved in memory. Therefore, no compiled file 2 can be seen when developing with webpack-dev-server. Hot update configures a plugin that comes with Webpack and also checks for module.hot in the main JS file

Plugins: [/ / hot update, it isn't refresh new webpack. HotModuleReplacementPlugin ()].Copy the code

Add the following code to the main JS file

if (module.hot){
    // Implement hot updates
    module.hot.accept();
}
Copy the code

Enable hot updates in webpack.config.js

devServer:{
        contentBase: "./dist",// The directory where the page is loaded by the local serverhistoryApiFallback: true,// do not jump to inline:truePort :3000, open:true// Automatically open the browser hot:true// Enable hot update},Copy the code

Hot updates allow various modules to be updated at run time without a full refresh.

Configuring an Html Template

1. Install the HTML-webpack-plugin

npm i html-webpack-plugin -D
Copy the code

2. Reference the plugin in webpack.config.js

const path=require('path');
let webpack=require('webpack');
let HtmlWebpackPlugin=require('html-webpack-plugin');
module.exports={
    entry:'./src/index.js'.output: {// Add hash to prevent file caching and generate a 4-bit hash string each time
        filename:'bundle.[hash:4].js'.path:path.resolve('dist')},// The following is the new configuration
    devServer:{
        contentBase: "./dist".// The directory where the page is loaded by the local server
        historyApiFallback: true./ / don't jump
        inline: true.// Refresh in real time
        port:3000.open:true.// Automatically open the browser
        hot:true  // Enable hot update
    },
    plugins: [new HtmlWebpackPlugin({
            template:'./src/index.html'.hash:true.// The hash string will be appended to the packaged bundle.js}})];Copy the code

Run NPM run build to do the packing, and each NPM run build will create a lot of packaged packages in the dist directory. You should always empty the dist directory before packing and put the packed files back in, using the clean-webpack-plugin. Run the NPM I clean-webpack-plugin -d command to install the plugin. The plug-in is then referenced in webpack.config.js.

const path=require('path');
let webpack=require('webpack');
let HtmlWebpackPlugin=require('html-webpack-plugin');
let CleanWebpackPlugin=require('clean-webpack-plugin');
module.exports={
    entry:'./src/index.js'.output: {// Add hash to prevent file caching and generate a 4-bit hash string each time
        filename:'bundle.[hash:4].js'.path:path.resolve('dist')},// The following is the new configuration
    devServer:{
        contentBase: "./dist".// The directory where the page is loaded by the local server
        historyApiFallback: true./ / don't jump
        inline: true.// Refresh in real time
        port:3000.open:true.// Automatically open the browser
        hot:true  // Enable hot update
    },
    plugins: [new HtmlWebpackPlugin({
            template:'./src/index.html'.hash:true.// The hash string will be appended to the packaged bundle.js
        }),
         Empty them before packing
        new CleanWebpackPlugin('dist')]};Copy the code

Then packaging will not produce redundant files.

Compile ES6 and JSX

1. Install Babel NPM I babel-core babel-loader babel-preset-env babel-preset-react babel-preset-stage-0 -d babel-loader Babel loader babel-preset-env: Only those features not yet supported are compiled based on the configured ENV. Babel-preset -react: JSX is converted to JS 2. Add the. Babelrc configuration file

{
  "presets": ["env"."stage-0"."react"] // From left to right}Copy the code

3. Modify the webpack. Config. Js

const path=require('path');
module.exports={
    entry:'./src/index.js'.output: {filename:'bundle.js'.path:path.resolve(__dirname,'dist')},// The following is the new configuration
    devServer:{
        contentBase: "./dist".// The directory where the page is loaded by the local server
        historyApiFallback: true./ / don't jump
        inline: true// Refresh in real time
    },
    module: {rules:[
            {
                test:/\.js$/.exclude:/(node_modules)/.// Remove nod_modules to optimize packaging speed
                use:{
                    loader:'babel-loader'}}]}};Copy the code

Development environment is separated from production environment

1. Install webpack – merge

npm install --save-dev webpack-merge
Copy the code

2. Create a webpack.common.js file as a public configuration file and write the following content:

const path=require('path');
let webpack=require('webpack');
let HtmlWebpackPlugin=require('html-webpack-plugin');
let CleanWebpackPlugin=require('clean-webpack-plugin');
module.exports={
    entry: ['babel-polyfill'.'./src/index.js'].output: {// Add hash to prevent file caching and generate a 4-bit hash string each time
        filename:'bundle.[hash:4].js'.path:path.resolve(__dirname,'dist')},plugins: [new HtmlWebpackPlugin({
            template:'./src/index.html'.hash:true.// The hash string will be appended to the packaged bundle.js
        }),
        Empty them before packing
        new CleanWebpackPlugin('dist'),
        new webpack.HotModuleReplacementPlugin()  // View the dependencies to patch].module: {rules:[
            {
                test:/\.js$/.exclude:/(node_modules)/.// Remove nod_modules to optimize packaging speed
                use:{
                    loader:'babel-loader'}}]}};Copy the code

3. Create a file named webpack.dev.js for the development environment configuration

const merge=require('webpack-merge');
const path=require('path');
let webpack=require('webpack');
const common=require('./webpack.common.js');
module.exports=merge(common,{
    devtool:'inline-soure-map'.mode:'development'.devServer: {historyApiFallback: true.// This is useful when developing a single page application. It relies on the HTML5 History API. If set to true, all jumps will point to index.html
        contentBase:path.resolve(__dirname, '.. /dist'),// The directory where the page is loaded by the local server
        inline: true.// Refresh in real time
        open:true.compress: true.port:3000.hot:true  // Enable hot update
    },
    plugins: [// Hot update, not refresh
        new webpack.HotModuleReplacementPlugin(),
    ],
});
Copy the code

4. Create a file named webpack.prod.js for the production environment configuration

 const merge = require('webpack-merge');
 const path=require('path');
 let webpack=require('webpack');
 const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
 const common = require('./webpack.common.js');
 module.exports = merge(common, {
     mode:'production'.plugins: [
         new UglifyJSPlugin()
     ]
 });
Copy the code

Configure the react

1. Install react, react-dom NPM I react react-dom-s 2. Create app.js and add the following.

import React from 'react';
class App extends React.Component{
    render(){
        return (<div>Jia jia go</div>); }}export default App;
Copy the code

3. Add the following content to index.js.

import React from 'react';
import ReactDOM from 'react-dom';
import {AppContainer} from 'react-hot-loader';
import App from './App';
ReactDOM.render(
    <AppContainer>
        <App/>
    </AppContainer>.document.getElementById('root'));if (module.hot) {
    module.hot.accept();
}
Copy the code

4. Install the react-hot-loader NPM i-d react-hot-loader 5. Add react-hot-loader/patch to the webpack.config.js entry value. Make sure to write it at the beginning of the entry. If you have “babel-polyfill” you write “babel-polyfill” 6. Add plugin to.babelrc,”plugins”: [“react-hot-loader/ Babel “]

Handle SASS

1. Install style-loader CSs-loader url-loader NPM install style-loader CSs-loader url-loader –save-dev 2. -sass NPM install sass-loader node-sass –save-dev 3. NPM install –save-dev mini-css-extract-plugin 4 install –save-dev mini-CSs-extract-plugin 4 Configure the webpack configuration file webpack.common.js

{
    test:/\.(png|jpg|gif)$/.use: ["url-loader"]},Copy the code

webpack.dev.js

{
    test:/\.scss$/.use: ["style-loader"."css-loader"."sass-loader"]}Copy the code

webpack.prod.js

 const merge = require('webpack-merge');
 const path=require('path');
 let webpack=require('webpack');
 const MiniCssExtractPlugin=require("mini-css-extract-plugin");
 const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
 const common = require('./webpack.common.js');
 module.exports = merge(common, {
     mode:'production'.module: {rules:[
             {
                 test:/\.scss$/.use: [// fallback to style-loader in developmentprocess.env.NODE_ENV ! = ='production' ? 'style-loader' : MiniCssExtractPlugin.loader,
                     "css-loader"."sass-loader"]]}},plugins: [
         new UglifyJSPlugin(),
         new MiniCssExtractPlugin({
             // Options similar to the same options in webpackOptions.output
             // both options are optional
             filename: "[name].css".chunkFilename: "[id].css"]}}));Copy the code