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 src2.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-dev3.wepback
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') // 打包后自动输出目录 } }package.json file scripts configuration
"scripts": { "build": "webpack" }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
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-devWebpack.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'] } ] } }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.csssrc/index.js file introduces 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-devwebpack.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 ] };After executing npm run build, we can see that there is an additional index.html file in the dist directory.
nbsp;html> <meta> <title>name</title> // 打包后的app.js已经被自动插入了html文件 <script></script>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
React's webpack configuration
Install react
npm install react react-dom --saveInstall 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
- 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 babel-loader configuration
// 在webpack.config.js 的modules.rules中加入此配置 { test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: 'babel-loader' } }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 nbsp;html> <meta> <title>Document</title> // react需要的渲染根元素 <p></p>
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 id="hello-world">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!

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.


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

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

Zend Studio 13.0.1
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version
Recommended: Win version, supports code prompts!
