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

How to build a webpack+react development environment

May 28, 2018 pm 03:41 PM
web develop

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

The environment mainly depends on the version

  1. webpack@4.8.1

  2. webpack-cli@2.1 .3

  3. ##webpack-dev-server@3.1.4
  4. react@16.3.2
  5. babel-core@6.26.3
  6. babel-preset-env@1.6.1
  7. ##bable-preset-react@6.24. 1
  8. webpack installation and configuration

1. Getting started

Create a new project directory, initialize npm, and create a new development source directory

mkdir webpack-react && cd webpack-react
npm init -y
mkdir src
Copy after login
2.webpack-cli

Starting from version 4.x, webpack and webpack-cli need to be installed at the same time (this tool is used to run webpack in the command line).

npm install webpack webpack-cli --save-dev
Copy after login
3.wepback

Configuration file

Create a new webpack.config.js file in the project root directory. This file is the core file for running webpack.

webpack.config.js basic configuration

// webpack.config.js
const path = require('path');
module.exports = {
  entry: './src/index.js',              // 入口文件
  output: {                       // webpack打包后出口文件
    filename: 'app.js',               // 打包后js文件名称
    path: path.resolve(dirname, 'dist')  // 打包后自动输出目录
  }
}
Copy after login
package.json file scripts configuration

"scripts": {
  "build": "webpack"
}
Copy after login
At this time, run npm run build on the command line to execute webpack, webpack It will automatically find the webpack.config.js file in the project root directory and perform packaging.

npm run build
// webpack打包后的项目
├── dist
│  └── app.js       // 打包后的app.js
├── package.json
├── src
│  └── index.js      // 源目录入口文件
└── webpack.config.js
Copy after login

webpack.config.js module related configuration

webpack treats all files as modules, pictures, css files, fonts and other static resources will be packaged into js files. Therefore, the loader file will be needed. More Loaders can query the URL. Next, we install some necessary Loader files.

npm install style-loader css-loader url-loader --save-dev
Copy after login
Webpack.config.js adds the module module

module.exports = {
 entry: './src/index.js',
 output: {
 filename: 'app.js',
 path: path.resolve(dirname, 'dist')
 },
 module: {
 rules: [
  {
  test: /\.css$/,
  use: ['style-loader', 'css-loader']
  },
  {
  test: /\.(png|svg|jpg|gif)$/,
  use: ['url-loader']
  },
  {
  test: /\.(woff|woff2|eot|ttf|otf)$/,
  use: ['url-loader']
  }
 ]
 }
}
Copy after login
After introducing the loader, you can import the css file or other static resources you want to introduce in your src/index.js file.

cd src && touch main.css
Copy after login
src/index.js file introduces css

import "./main.css";
Copy after login

webpack.config.js plugins configuration

Main js files and static files can be After successfully packaging it into a js file, we need to put the js file into an html file. The webpack plug-in ***html-webpack-plugin*** does this. It can automatically generate an html file and put us Put the packaged js files into html.

npm install html-webpack-plugin --save-dev
Copy after login
webpack.config.js Configure plugins

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin'); // 引入插件
module.exports = {
 entry: './src/index.js',
 output: {
 filename: 'app.js',
 path: path.resolve(dirname, 'dist')
 },
 module: {
 rules: [
  {
  test: /\.css$/,
  use: ['style-loader', 'css-loader']
  },
  {
  test: /\.(png|svg|jpg|gif)$/,
  use: ['url-loader']
  },
  {
  test: /\.(woff|woff2|eot|ttf|otf)$/,
  use: ['url-loader']
  }
 ]
 },
 plugins: [
 new HtmlWebpackPlugin({title: 'production'}) // 配置plugin
 ]
};
Copy after login
After executing npm run build, we can see that there is an additional index.html file in the dist directory.

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title>name</title>
 </head>
 <body>
 // 打包后的app.js已经被自动插入了html文件
 <script type="text/javascript" src="app.js"></script></body>
</html>
Copy after login
At this point, the simplest and most basic requirements of webpack have been configured. At this time, the project structure is:

├── dist            // 生产目录
│  ├── app.js
│  └── index.html
├── package.json
├── src            // 源目录
│  ├── index.js
│  └── main.css
└── webpack.config.js
Copy after login

React's webpack configuration

Install react

npm install react react-dom --save
Copy after login
Install react, wepback conversion dependency

React components are composed of JSX. Browsers cannot recognize JSX and need to be converted by Babel.

babel-croe is the babel core file
  1. babel-preset-env escapes ES6 to ES5
  2. babel-preset-react Escape JSX to js
  3. babel-loader webpack’s babe conversion
  4. Copy Code
The code is as follows:

npm install babel-core babel-preset-env babel-preset-react babel-loader --save-dev

##.babelrc configuration file

Create a new .babelrc file in the project root directory. This file is the core configuration of babel. Babel will automatically recognize it in the project root directory.

// .babelrc
{
 "presets": ["env", "react"]
}
Copy after login
webpack babel-loader configuration

// 在webpack.config.js 的modules.rules中加入此配置
{
 test: /\.(js|jsx)$/,
 exclude: /node_modules/,
 use: {
 loader: 'babel-loader'
 }
}
Copy after login

html-webpack-plugin template configuration

We know that react needs to get a root element of the page, and then render It will take effect. We can create a new html file and let the html-webpack-plugin plug-in package based on this file. So we create a new html file in the root directory and use this file as a template.

// index.html
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
</head>
<body>
    // react需要的渲染根元素
 <p id="root"></p>
</body>
</html>
Copy after login

At this time webpack.config.js configuration:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
 entry: './src/index.js',
 output: {
 filename: 'app.js',
 path: path.resolve(dirname, 'dist')
 },
 module: {
 rules: [
  {
  test: /\.(js|jsx)$/,
  exclude: /node_modules/,
  use: {
   loader: 'babel-loader'
  }
  },
  {
  test: /\.css$/,
  use: ['style-loader', 'css-loader']
  },
  {
  test: /\.(png|svg|jpg|gif)$/,
  use: ['url-loader']
  },
  {
  test: /\.(woff|woff2|eot|ttf|otf)$/,
  use: ['url-loader']
  }
 ]
 },
 plugins: [
 new HtmlWebpackPlugin({
  title: 'production',
  template: './index.html'  // 模板文件位置
 }) 
 ]
};
Copy after login

Write React and run webpack

// src/index.js
import React from 'react';
import ReactDom from 'react-dom';
import './main.css'
ReactDom.render(
 <h1>hello world</h1>,
 document.getElementById('root')
);
Copy after login

运行npm run build,生成dist目录,打开dist目录中的index.html文件,可以发现浏览器已正常渲染"hello world"。

dev环境热更新配置

react的wepack完成以后,是不是发现每修改一次代码,想看到效果,得重新打包一次才行。webpack-dev-server配置可以帮助我们实现热更新,在开发环境解放我们的生产力。

安装webpack-dev-server

npm install webpack-dev-server --save-dev
Copy after login

webpack.config.js 配置

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = {
 entry: './src/index.js',
 output: {
 filename: 'app.js',
 path: path.resolve(dirname, 'dist')
 },
 module: {
 rules: [
  {
  test: /\.(js|jsx)$/,
  exclude: /node_modules/,
  use: {
   loader: 'babel-loader'
  }
  },
  {
  test: /\.css$/,
  use: ['style-loader', 'css-loader']
  },
  {
  test: /\.(png|svg|jpg|gif)$/,
  use: ['url-loader']
  },
  {
  test: /\.(woff|woff2|eot|ttf|otf)$/,
  use: ['url-loader']
  }
 ]
 },
 plugins: [
 new HtmlWebpackPlugin({
  title: 'production',
  template: './index.html'  
 }),
 // hot 检测文件改动替换plugin
 new webpack.NamedModulesPlugin(),   
 new webpack.HotModuleReplacementPlugin() 
 ],
    // webpack-dev-server 配置
 devServer: {
 contentBase: './dist',
 hot: true
 },
};
Copy after login

运行webpack-dev-server

在 package.json 文件 加入 scripts 配置:

"scripts": {
 "build": "webpack",
 "dev": "webpack-dev-server --open --mode development" // webpack-dev-server
},
Copy after login

命令行运行 npm run dev

可以在浏览器中输入localhost:8080 内容即为dist目录下的index.html内容。修改src/index.js中的内容或者依赖,即实时在浏览器热更新看到。

至此,react的webpack的基础开发环境已全部配置完毕。

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

推荐阅读:

怎样使用JS实现调用本地摄像头

怎样使用JS实现3des+base64加密解密算法

The above is the detailed content of How to build a webpack+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)

Four recommended AI-assisted programming tools Four recommended AI-assisted programming tools Apr 22, 2024 pm 05:34 PM

This AI-assisted programming tool has unearthed a large number of useful AI-assisted programming tools in this stage of rapid AI development. AI-assisted programming tools can improve development efficiency, improve code quality, and reduce bug rates. They are important assistants in the modern software development process. Today Dayao will share with you 4 AI-assisted programming tools (and all support C# language). I hope it will be helpful to everyone. https://github.com/YSGStudyHards/DotNetGuide1.GitHubCopilotGitHubCopilot is an AI coding assistant that helps you write code faster and with less effort, so you can focus more on problem solving and collaboration. Git

Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Apr 07, 2024 am 09:10 AM

On March 3, 2022, less than a month after the birth of the world's first AI programmer Devin, the NLP team of Princeton University developed an open source AI programmer SWE-agent. It leverages the GPT-4 model to automatically resolve issues in GitHub repositories. SWE-agent's performance on the SWE-bench test set is similar to Devin, taking an average of 93 seconds and solving 12.29% of the problems. By interacting with a dedicated terminal, SWE-agent can open and search file contents, use automatic syntax checking, edit specific lines, and write and execute tests. (Note: The above content is a slight adjustment of the original content, but the key information in the original text is retained and does not exceed the specified word limit.) SWE-A

Summary of the five most popular Go language libraries: essential tools for development Summary of the five most popular Go language libraries: essential tools for development Feb 22, 2024 pm 02:33 PM

Summary of the five most popular Go language libraries: essential tools for development, requiring specific code examples. Since its birth, the Go language has received widespread attention and application. As an emerging efficient and concise programming language, Go's rapid development is inseparable from the support of rich open source libraries. This article will introduce the five most popular Go language libraries. These libraries play a vital role in Go development and provide developers with powerful functions and a convenient development experience. At the same time, in order to better understand the uses and functions of these libraries, we will explain them with specific code examples.

Learn how to develop mobile applications using Go language Learn how to develop mobile applications using Go language Mar 28, 2024 pm 10:00 PM

Go language development mobile application tutorial As the mobile application market continues to boom, more and more developers are beginning to explore how to use Go language to develop mobile applications. As a simple and efficient programming language, Go language has also shown strong potential in mobile application development. This article will introduce in detail how to use Go language to develop mobile applications, and attach specific code examples to help readers get started quickly and start developing their own mobile applications. 1. Preparation Before starting, we need to prepare the development environment and tools. head

Which Linux distribution is best for Android development? Which Linux distribution is best for Android development? Mar 14, 2024 pm 12:30 PM

Android development is a busy and exciting job, and choosing a suitable Linux distribution for development is particularly important. Among the many Linux distributions, which one is most suitable for Android development? This article will explore this issue from several aspects and give specific code examples. First, let’s take a look at several currently popular Linux distributions: Ubuntu, Fedora, Debian, CentOS, etc. They all have their own advantages and characteristics.

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

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Understanding VSCode: What is this tool used for? Understanding VSCode: What is this tool used for? Mar 25, 2024 pm 03:06 PM

&quot;Understanding VSCode: What is this tool used for?&quot; 》As a programmer, whether you are a beginner or an experienced developer, you cannot do without the use of code editing tools. Among many editing tools, Visual Studio Code (VSCode for short) is very popular among developers as an open source, lightweight, and powerful code editor. So, what exactly is VSCode used for? This article will delve into the functions and uses of VSCode and provide specific code examples to help readers

See all articles