Home Web Front-end JS Tutorial How to use webpack to build a react development environment

How to use webpack to build a react development environment

May 29, 2018 pm 05:30 PM
react web webpack

This time I will show you how to use webpack to build a react development environment, and what are the precautions for using webpack to build a react development environment. The following is a practical case, let's take a look.

1.Initialize the project

mkdir react-redux && cd react-redux
npm init -y
Copy after login

2. Install webpack

npm i webpack -D
Copy after login
npm i -D It is the abbreviation of npm install --save-dev, which refers to installing modules and saving them in the devDependencies of package.json, mainly dependency packages in the development environment. If you use webpack 4 version, you also need to install the CLI.

npm install -D webpack webpack-cli
Copy after login

3. Create a new project structure

react-redux
 |- package.json
+ |- /dist
+  |- index.html
 |- /src
  |- index.js
Copy after login
index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<p id="root"></p>
<script src="bundle.js"></script>
</body>
</html>
Copy after login
index.js

document.querySelector('#root').innerHTML = 'webpack使用';
Copy after login
Non-global installation of packaging.

node_modules\.bin\webpack src\index.js --output dist\bundle.js --mode development
Copy after login
Open the html in the dist directory to display webpack and use

to configure 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 after login
Run command:

node_modules\.bin\webpack --mode production You can package 2.NPM Scripts (NPM Scripts) Add an npm script in package.json (npm script): "build": "webpack --mode production" Run npm run build to package

Build using webpack Local server

webpack-dev-server provides a simple web server and can be reloaded in real time.

1. Installation

npm i -D webpack-dev-server Modify the configuration file webpack.config.js

const path=require('path');
module.exports={
  entry:'./src/index.js',
  output:{
    filename:'bundle.js',
    path:path.resolve(dirname,'dist')
  },
  //以下是新增的配置
  devServer:{
    contentBase: "./dist",//本地服务器所加载的页面所在的目录
    historyApiFallback: true,//不跳转
    inline: true,//实时刷新
    port:3000,
    open:true,//自动打开浏览器
  }
};
Copy after login
Run webpack-dev-server --progress, browse The server opens localhost:3000, and the modified code will display the modified results in real time. Add the scripts script and run npm start to automatically open http://localhost:8080/

"start": "webpack-dev-server --open --mode development"
Copy after login
After starting webpack-dev-server, in the target file The compiled files cannot be seen in the folder, and the files compiled in real time are saved in the memory. Therefore, when using webpack-dev-server for development, you cannot see the compiled files

2. Hot update

Configure a plug-in that comes with webpack and also include it in the main js file Check if there is module.hot

plugins:[
    //热更新,不是刷新
    new webpack.HotModuleReplacementPlugin()
  ],
Copy after login
Add the following code in the main js file

if (module.hot){
  //实现热更新
  module.hot.accept();
}
Copy after login
Enable hot update in webpack.config.js

devServer:{
    contentBase: "./dist",//本地服务器所加载的页面所在的目录
    historyApiFallback: true,//不跳转
    inline: true,//实时刷新
    port:3000,
    open:true,//自动打开浏览器
    hot:true //开启热更新
  },
Copy after login
Hot update is allowed to run Update various modules without the need for a complete refresh.

Configure Html template

1. Install the html-webpack-plugin plugin

npm i html-webpack-plugin -D
Copy after login
2. Reference the plug-in 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:{
    //添加hash可以防止文件缓存,每次都会生成4位hash串
    filename:'bundle.[hash:4].js',
    path:path.resolve('dist')
  },
  //以下是新增的配置
  devServer:{
    contentBase: "./dist",//本地服务器所加载的页面所在的目录
    historyApiFallback: true,//不跳转
    inline: true,//实时刷新
    port:3000,
    open:true,//自动打开浏览器
    hot:true //开启热更新
  },
  plugins:[
    new HtmlWebpackPlugin({
      template:'./src/index.html',
      hash:true, //会在打包好的bundle.js后面加上hash串
    })
  ]
};
Copy after login
Run

npm run build for packaging. At this time, it will be in the dist directory every time npm run build Create a lot of packaged packages. You should clear the files in the dist directory before each package, and then put the packaged files into it. The clean-webpack-plugin plug-in is used here. Pass npm i clean-webpack-plugin -D command to install. Then reference the plug-in 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:{
    //添加hash可以防止文件缓存,每次都会生成4位hash串
    filename:'bundle.[hash:4].js',
    path:path.resolve('dist')
  },
  //以下是新增的配置
  devServer:{
    contentBase: "./dist",//本地服务器所加载的页面所在的目录
    historyApiFallback: true,//不跳转
    inline: true,//实时刷新
    port:3000,
    open:true,//自动打开浏览器
    hot:true //开启热更新
  },
  plugins:[
    new HtmlWebpackPlugin({
      template:'./src/index.html',
      hash:true, //会在打包好的bundle.js后面加上hash串
    }),
     //打包前先清空
    new CleanWebpackPlugin('dist')
  ]
};
Copy after login
After packaging, no extra files will be generated.

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 : babelLoader babel-preset-env: Only compiles features that are not yet supported according to the configured env. babel-preset-react: Convert jsx to js

2. Add .babelrc configuration file

{
 "presets": ["env", "stage-0","react"] //从左向右解析
}
Copy after login
3. Modify webpack.config.js

const path=require('path');
module.exports={
  entry:'./src/index.js',
  output:{
    filename:'bundle.js',
    path:path.resolve(dirname,'dist')
  },
  //以下是新增的配置
  devServer:{
    contentBase: "./dist",//本地服务器所加载的页面所在的目录
    historyApiFallback: true,//不跳转
    inline: true//实时刷新
  },
  module:{
    rules:[
      {
        test:/\.js$/,
        exclude:/(node_modules)/, //排除掉nod_modules,优化打包速度
        use:{
          loader:'babel-loader'
        }
      }
    ]
  }
};
Copy after login

Separation of development environment and production environment

1. Install webpack-merge

npm install --save-dev webpack-merge
Copy after login
2. Create a new file named webpack.common.js as a public configuration 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:{
    //添加hash可以防止文件缓存,每次都会生成4位hash串
    filename:'bundle.[hash:4].js',
    path:path.resolve(dirname,'dist')
  },
  plugins:[
    new HtmlWebpackPlugin({
      template:'./src/index.html',
      hash:true, //会在打包好的bundle.js后面加上hash串
    }),
    //打包前先清空
    new CleanWebpackPlugin('dist'),
    new webpack.HotModuleReplacementPlugin() //查看要修补(patch)的依赖
  ],
  module:{
    rules:[
      {
        test:/\.js$/,
        exclude:/(node_modules)/, //排除掉nod_modules,优化打包速度
        use:{
          loader:'babel-loader'
        }
      }
    ]
  }
};
Copy after login
3. Create a new file named webpack.dev.js as 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, //在开发单页应用时非常有用,它依赖于HTML5 history API,如果设置为true,所有的跳转将指向index.html
    contentBase:path.resolve(dirname, '../dist'),//本地服务器所加载的页面所在的目录
    inline: true,//实时刷新
    open:true,
    compress: true,
    port:3000,
    hot:true //开启热更新
  },
  plugins:[
    //热更新,不是刷新
    new webpack.HotModuleReplacementPlugin(),
  ],
});
Copy after login
4. Create a new file named webpack.prod.js as 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 after login

Configure react

1. Install react,

react-dom npm i react react-dom -S
Copy after login
2. Create a new App.js and add the following content.

import React from 'react';
class App extends React.Component{
  render(){
    return (<p>佳佳加油</p>);
  }
}
export default App;
Copy after login
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 after login

4.安装 react-hot-loader

npm i -D react-hot-loader
Copy after login

5.修改配置文件 在 webpack.config.js 的 entry 值里加上 react-hot-loader/patch,一定要写在entry 的最前面,如果有 babel-polyfill 就写在babel-polyfill 的后面

6.在 .babelrc 里添加 plugin, "plugins": ["react-hot-loader/babel"]

处理SASS

1.安装 style-loader css-loader url-loader

npm install style-loader css-loader url-loader --save-dev
Copy after login

2.安装 sass-loader node-sass

npm install sass-loader node-sass --save-dev
Copy after login

3.安装 mini-css-extract-plugin ,提取单独打包css文件

npm install --save-dev mini-css-extract-plugin
Copy after login

4.配置webpack配置文件

webpack.common.js

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

webpack.dev.js

{
  test:/\.scss$/,
  use:[
    "style-loader",
    "css-loader",
    "sass-loader"
  ]
}
Copy after login

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 development
           process.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 after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

详细解析微信小程序入门教程+案例

怎样使用angularjs中http服务器

The above is the detailed content of How to use webpack to build a react development environment. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

React Router User Guide: How to implement front-end routing control React Router User Guide: How to implement front-end routing control Sep 29, 2023 pm 05:45 PM

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

PHP, Vue and React: How to choose the most suitable front-end framework? PHP, Vue and React: How to choose the most suitable front-end framework? Mar 15, 2024 pm 05:48 PM

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

Integration of Java framework and front-end React framework Integration of Java framework and front-end React framework Jun 01, 2024 pm 03:16 PM

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

What are web standards? What are web standards? Oct 18, 2023 pm 05:24 PM

Web standards are a set of specifications and guidelines developed by W3C and other related organizations. It includes standardization of HTML, CSS, JavaScript, DOM, Web accessibility and performance optimization. By following these standards, the compatibility of pages can be improved. , accessibility, maintainability and performance. The goal of web standards is to enable web content to be displayed and interacted consistently on different platforms, browsers and devices, providing better user experience and development efficiency.

How to enable administrative access from the cockpit web UI How to enable administrative access from the cockpit web UI Mar 20, 2024 pm 06:56 PM

Cockpit is a web-based graphical interface for Linux servers. It is mainly intended to make managing Linux servers easier for new/expert users. In this article, we will discuss Cockpit access modes and how to switch administrative access to Cockpit from CockpitWebUI. Content Topics: Cockpit Entry Modes Finding the Current Cockpit Access Mode Enable Administrative Access for Cockpit from CockpitWebUI Disabling Administrative Access for Cockpit from CockpitWebUI Conclusion Cockpit Entry Modes The cockpit has two access modes: Restricted Access: This is the default for the cockpit access mode. In this access mode you cannot access the web user from the cockpit

what does web mean what does web mean Jan 09, 2024 pm 04:50 PM

The web is a global wide area network, also known as the World Wide Web, which is an application form of the Internet. The Web is an information system based on hypertext and hypermedia, which allows users to browse and obtain information by jumping between different web pages through hyperlinks. The basis of the Web is the Internet, which uses unified and standardized protocols and languages ​​to enable data exchange and information sharing between different computers.

Is PHP front-end or back-end in web development? Is PHP front-end or back-end in web development? Mar 24, 2024 pm 02:18 PM

PHP belongs to the backend in web development. PHP is a server-side scripting language, mainly used to process server-side logic and generate dynamic web content. Compared with front-end technology, PHP is more used for back-end operations such as interacting with databases, processing user requests, and generating page content. Next, specific code examples will be used to illustrate the application of PHP in back-end development. First, let's look at a simple PHP code example for connecting to a database and querying data:

How to implement h5 to slide up on the web side to load the next page How to implement h5 to slide up on the web side to load the next page Mar 11, 2024 am 10:26 AM

Implementation steps: 1. Monitor the scroll event of the page; 2. Determine whether the page has scrolled to the bottom; 3. Load the next page of data; 4. Update the page scroll position.

See all articles