search
HomeWeb Front-endJS TutorialHow to configure react development environment? React+webpack development environment configuration steps (in-depth article)

This article mainly talks about the in-depth understanding of the development environment configuration steps of react webpack. Now let’s read this article together

Here we will first explain the reasons and practices of each step. Other articles will talk about how to quickly build webpack, which doesn’t have to be so complicated. Configure basic article link: http://www.php.cn/js-tutorial-409770.html

Transfer to the above directory:

Directory
2. Webpack upgrade
6. ES6 to ES5 module
7. URL and file module
3. Webpack advanced chapter
1. Syntax checker eslint
2.uglify source code encryption and compression
3.moduleconcatenationPlugin
4.devtool
5.happypack
6.dll

6.ES6 to ES5 module

Because some browsers do not support the ES6 part The syntax is not fully compatible, but nodejs already supports ES6, so webpack provides an ES6 to ES5 module.
Installation instructions (used in development mode):

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

If you want to support react, you need to install the following modules:

npm install babel-preset-es2015 babel-preset-react babel-preset-stage-3 --save-dev

Webpack.config.js code:

module.exports = {...module:{    
    rules:[...
   {
        test:/\.jsx$/,
        exclude:/(node_modules|bower_components)/,//排除XXX类型文件
        use:{
            loader:'babel-loader'           
        }
    }
]
}...}

Create the .babelrc file under the root path

{
  "presets": ["es2015","react"]}

7.url and file modules
Introduce the url module to process images, and the file module to process other file types other than images
Instructions:

npm install url-loader file-loader --save-dev

webpack.config.js Code:

module.exports = {...
    {   //配置辅助loader,处理图片  
        test:/\.(png|jpg|gif)$/,
        loader:'url-loader',
        options:{limit:8192,name:"images/[name].[ext]"}
    },
    { //处理图片外的其他文件类型
        test:/\.(appcache|svg|eot|ttf|woff|woff2|mp3|pdf)(\?|$)/,
        include:path.resolve(__dirname,'src'),
        loader:'file-loader?name=[name].[ext]' 
    }...}

3. Advanced webpack
1. Syntax checker eslint
ESLint is a QA tool used to avoid low-level errors and unify the code style .
Installation instructions:

npm install eslint eslint-loader --save-dev

After installing eslint, then create a rule file through the init command.

指令:
cd 进入项目文件夹根路径,敲./node_modules/.bin/eslint --init  

? How would you like to configure ESLint? Answer questions about your style
? Are you using ECMAScript 6 features? Yes
? Are you using ES6 modules? Yes
? Where will your code run? Browser, Node
? Do you use CommonJS? Yes
? Do you use JSX? Yes
? Do you use React? Yes
? What style of indentation do you use? Tabs
? What quotes do you use for strings? Single? What line endings do you use? Windows
? Do you require semicolons? Yes
? What format do you want your config file to be in? JSON

After answering the question, a file in .eslintrc.json format will be generated under the root directory, and the corresponding package will be automatically installed. .eslintrc.json
The content inside can be fine-tuned according to your own programming habits. ESLINT Chinese website
Here is an example:

{    "env": {        "browser": true,        "commonjs": true,        "es6": true,        "node": true
    },    "extends": "plugin:react/recommended",    "parserOptions": {        "ecmaVersion": 8,//ECMAScript syntax 最新版本
        "ecmaFeatures": {            "impliedStrict": true,            "experimentalObjectRestSpread": true,            "jsx": true
        },        "sourceType": "module"
    },    "plugins": [        "react"
    ],    "rules": {        "semi": [            "error",            "always"
        ],              
        "no-debugger": "error",//不允许用debugger这个关键字
        "no-dupe-args": "error",//不允许函数参数同名
        "no-caller": "error",//不允许用callee等,es6严格模式不支持
        "no-unmodified-loop-condition": "error",        "no-with": "error",//不允许用with来声明
        "no-catch-shadow": "error"
    }
}

Webpack.config.js configuration

module: {
        rules: [        ...{
        test:/\.js$/,
        enforce:'pre',
       loader:'eslint-loader',
       include:path.resolve(__dirname,'src')
    }...]
}

2.uglify source code encryption and compression (if you want to see more, go to PHP Chinese Learn in the column of the NetReact Reference Manual)

is a plug-in of webpack, just use it directly.

webpack.config.js 代码:
module.exports = {   ...
 plugins:[
 ..  
new webpack.optimize.UglifyJsPlugin(
{output: { 
    comments:false,//删除代码中所有注释
},
compress:{
 warnings:false,
}
})
]...}

4.devtool
The auxiliary tool provided by webpack can correctly display the number of error lines in the source code during debugging. eval-soure-map is used in development mode. Other parameters use the environment

module.exports = {...devtool:'eval-soure-map'...}

5.happypack
Let the loader process the file to speed up the webpack construction

安装指令:npm install happypack --save-dev
var os = require('os');//os.cpus().Length 一般会取不到值,这里直接size:4,而不是size:os.cpus().lengthvar Happypack = require('happypack');var happypackThreadPool = Happypack.ThreadPool({size:4});//size:os.cpus().Lengt根据电脑的idle,配置当前最大的线程数量module.config.js 下面的配置module.exports = {
...module:{    rules:[
 {        test:/\.js$/,    
        include:path.resolve(__dirname),        loader:'happypack/loader?id=happybabel'

    }
]
}plugins:[new Happypack({    id:"happybabel",    loaders:['babel-loader'],    threadPool:happypackThreadPool,    cache:true,    verbose:true}),
]
}

6.dll
Create a webpack.dll in the root directory .config.js file

//webpack.dll.config.js 的内容:const webpack = require('webpack');const path = require("path");const fs=require('fs');const vendors = [  'react' //这里添加第三方库文件

];module.exports = {  entry: {    vendor: vendors,
  },  output: {    path: path.join(__dirname+'/build'),    filename: '[name].[chunkhash].js',    library: '[name]_[chunkhash]',
  },  plugins: [    new webpack.DllPlugin({      path: path.join(__dirname+"/build"+'/manifest.json'),      name: '[name]_[chunkhash]',      context: __dirname,
    }),
  ],
};//console.log(path.join(__dirname+"/build"));

Type the following command in the Powershell window:

webpack --config webpack.dll.config.js -p

Two files will be generated in the build path, one is manifest.json and the other is vendor.XXXX.js document. vendor.xxx.js needs to be introduced in html (written directly in the html template here).
webpack.config.js Fill in:

 moule.exports = { ...
 plugins:[  ...
 new webpack.DllReferencePlugin({
      context: __dirname,
      manifest: require('./build/manifest.json'),
    }),    ...]
....
}

Then type npm start in Powershell.

This article ends here (if you want to see more, go to the PHP Chinese website React User Manual column to learn). If you have any questions, you can leave a message below.

The above is the detailed content of How to configure react development environment? React+webpack development environment configuration steps (in-depth article). For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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 Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor