How to build a webpack+react development environment
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
- webpack@4.8.1
- webpack-cli@2.1 .3 ##webpack-dev-server@3.1.4
- react@16.3.2
- babel-core@6.26.3
- babel-preset-env@1.6.1
- ##bable-preset-react@6.24. 1
- webpack installation and configuration
1. Getting started
Create a new project directory, initialize npm, and create a new development source directorymkdir webpack-react && cd webpack-react npm init -y mkdir src
npm install webpack webpack-cli --save-dev
Configuration file
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') // 打包后自动输出目录 } }
"scripts": { "build": "webpack" }
npm run build // webpack打包后的项目 ├── dist │ └── app.js // 打包后的app.js ├── package.json ├── src │ └── index.js // 源目录入口文件 └── webpack.config.js
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
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'] } ] } }
cd src && touch main.css
import "./main.css";
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
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 ] };
<!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>
├── dist // 生产目录 │ ├── app.js │ └── index.html ├── package.json ├── src // 源目录 │ ├── index.js │ └── main.css └── webpack.config.js
React's webpack configuration
Install react
npm install react react-dom --save
- babel-preset-env escapes ES6 to ES5
- babel-preset-react Escape JSX to js
- babel-loader webpack’s babe conversion
- Copy Code
npm install babel-core babel-preset-env babel-preset-react babel-loader --save-dev
##.babelrc configuration fileCreate 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"]
}
// 在webpack.config.js 的modules.rules中加入此配置 { test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: 'babel-loader' } }
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>
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' // 模板文件位置 }) ] };
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') );
运行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
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 }, };
运行webpack-dev-server
在 package.json 文件 加入 scripts 配置:
"scripts": { "build": "webpack", "dev": "webpack-dev-server --open --mode development" // webpack-dev-server },
命令行运行 npm run dev
可以在浏览器中输入localhost:8080 内容即为dist目录下的index.html内容。修改src/index.js中的内容或者依赖,即实时在浏览器热更新看到。
至此,react的webpack的基础开发环境已全部配置完毕。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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

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.

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.

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

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?" 》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
