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.
mkdir react-redux && cd react-redux npm init -y
2. Install webpack
npm i webpack -Dnpm 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
3. Create a new project structure
react-redux |- package.json + |- /dist + |- index.html |- /src |- index.jsindex.html
nbsp;html> <meta> <title>Title</title> <p></p> <script></script>index.js
document.querySelector('#root').innerHTML = 'webpack使用';Non-global installation of packaging.
node_modules\.bin\webpack src\index.js --output dist\bundle.js --mode developmentOpen the html in the dist directory to display webpack and use
to configure webpack
1. Use theconst path=require('path'); module.exports={ entry:'./src/index.js', output:{ filename:'bundle.js', path:path.resolve(dirname,'dist') } };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,//自动打开浏览器 } };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"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 files2. Hot updateConfigure 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() ],Add the following code in the main js file
if (module.hot){ //实现热更新 module.hot.accept(); }Enable hot update in webpack.config.js
devServer:{ contentBase: "./dist",//本地服务器所加载的页面所在的目录 historyApiFallback: true,//不跳转 inline: true,//实时刷新 port:3000, open:true,//自动打开浏览器 hot:true //开启热更新 },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 pluginnpm i html-webpack-plugin -D2. 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串 }) ] };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') ] };After packaging, no extra files will be generated.
Compile es6 and jsx
1. Install babelnpm 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
{ "presets": ["env", "stage-0","react"] //从左向右解析 }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' } } ] } };
Separation of development environment and production environment
1. Install webpack-mergenpm install --save-dev webpack-merge2. 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' } } ] } };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(), ], });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() ] });
Configure react
1. Install react,react-dom npm i react react-dom -S2. 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;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></app> </appcontainer>, document.getElementById('root') ); if (module.hot) { module.hot.accept(); }
4.安装 react-hot-loader
npm i -D react-hot-loader
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
2.安装 sass-loader node-sass
npm install sass-loader node-sass --save-dev
3.安装 mini-css-extract-plugin ,提取单独打包css文件
npm install --save-dev mini-css-extract-plugin
4.配置webpack配置文件
webpack.common.js
{ test:/\.(png|jpg|gif)$/, use:[ "url-loader" ] },
webpack.dev.js
{ test:/\.scss$/, use:[ "style-loader", "css-loader", "sass-loader" ] }
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" }) ] });
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
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!

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.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.


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

Atom editor mac version download
The most popular open source editor

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.

Dreamweaver CS6
Visual web development tools

SublimeText3 Chinese version
Chinese version, very easy to use

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
