Construction of react project based on Webpack (II.)

Source: Internet
Author: User

Objective

We have already built the basic environment, and now we will make the development environment more perfect.

    • Devtool

During the development process, we will often debug, so, in order to facilitate our debugging of source code in Chrome, we need to change webpack.config.js and then launch Webpack-dev-server. After completing the debug in Chrome browser, click the Sources option, you can see the prompt, and then enter the source file name you want to view to display the file source code, if you think there is a problem with the code, the corresponding line number on the breakpoint can be debugged.

= {    ' cheap-module-eval-source-map ',    ...}

    • Hot Update (HMR)

HMR should be a very exciting feature of Webpack, which is repackaged and sent to the browser after the code has been modified, and the browser replaces the old module with the new module, which implements updates to the app without refreshing the browser. Since we are using Webpack-dev-server, it offers two automatic refresh modes for our selection, iframe and inline mode. Here we select the inline mode and change the dev-server.js.

......
New webpackdevserver (compiler, { /// default will provide the local server in the root folder, where the folder is specified inline:true // Auto Refresh hot:true // turn on Hot module replacement
......

Change Webpack.config.js

......
Const WEBPACK = require (' Webpack ');
Module.exports = { ' cheap-module-eval-source-map ', entry: [
     ' webpack-dev-server/client?http://localhost:9090 ', ' webpack/hot/only-dev-server ', '. /src/index.js ') ],
...... plugins: [ new Webpack. Hotmodulereplacementplugin () ]

Last Change Index.js

Import React from ' React 'react-dom'./app '= Component = {    render (         <component/>,        document.getElementById (' app ')    ;} Renderdom (APP); if (module.hot) {    module.hot.accept ('./app ', () = {        Const APP = require ('./app '). Default;        Renderdom (APP);}    )}

Next, run NPM run Dev and look at the browser and discover that the thermal update is implemented as follows.

Then modify the HTML returned by render in App.js, and save it to discover that the browser will automatically refresh and see the effect you have changed. Perhaps this enables the thermal update of the react component, right? Let's make the following changes to App.js to see what will change.

Import React, {Component} from ' React 'default  class App extends Component {    constructor (p Rops) {        super (props);          this.state = {            count:1,        }    }    Add () {        this.setstate ({count:this.state.count + 1});    };    render () {        return (            <div>                        );    }}

Then click on the button in the browser, the value of the page increases. Then, we modify the App.js (add another tag under the Button tab), the browser automatically refreshes after saving. We look at the browser, then the problem is, just click on the added value is gone, and back to the initial value of 1. At this point the state of the component is not saved, and the REACT hot update is not reached in real sense. So there is also a need to introduce a plugin to help us solve the problem of hot Update component state preservation. This is also the origin of React-hot-loader.

NPM Install React-hot-loader--save-dev

Change the webpack.config.js.

......
Module.exports = { ' cheap-module-eval-source-map ', entry: [ ' Babel-polyfill ', ' react-hot-loader/patch ', ' webpack-dev-server/client?http://localhost:8080 ', ' Webpack/hot/only-dev-server ',
......

Change the index.js.

......
Import {Appcontainer} from ' React-hot-loader '; import ' Babel-polyfill ';'. /app '= Component = { render ( <AppContainer> <component/> </appcontainer>, document.getElementById (' app '); };
......

Change. BABELRC.

{  "presets": [    [      "es2015",      {        "module": false      }    ],     "React"  ],  "plugins": [    "React-hot-loader/babel"] }

Once modified, npm run dev needs to be re -executed. We repeat the above operation, we can find that no longer the above problem. Of course, the above react function bindings are also written in several ways:

//Way One<button onclick={() = This. Add ()}> add 1</button>//Mode two<button onclick={ This. Add.bind ( This)}>count+1</button>//method Three, the official recommended useConstructor (props) {super (props) This. Add = This. Add.bind ( This);}<button onclick={ This. Add)}>count+1</button>//mode four, recommended (because it is in the draft phase, so it is used in the form of plugins)
Add = () = {
......
}<button onclick={ This. Add)}>count+1</button>

I prefer the fourth kind, more concise. Here we configure the fourth way.

NPM Install babel-preset-stage-1--save

Last modified. BABELRC can be.

......
"React","Stage-1"
......
    • Eslint syntax Check

A JavaScript grammar detection tool that can statically detect code errors and hints like an IDE. Install eslint and eslint-loaderfirst.

NPM Install Eslint Eslint-loader--save-dev

Modify the Webpack.config.js.

......
Module: { rules: [ { "pre", test:/\. JS|JSX) $/, loader: ' Eslint-loader ', exclude:/node_modules/ },
......

New. Eslintrc.json under the project root directory.

{  "rules": {  }}

We do not create the rules, run the report error parsing error:the keyword ' import ' is reserved, because the project uses a new syntax such as ES6, and these are not directly recognized, so it is necessary to install Babel-eslint is escaped.

NPM Install Babel-eslint--save-dev

Modify the. eslintrc.json file.

{  "parser": "Babel-eslint",  "rules": {  }}

Once the above modifications are complete, you can rerun. Here, we can start customizing the rules, and you can open up your own rules for everyone to use. However, it is not practical to have all the custom rules from start to finish, but fortunately there are many rules that conform to best practices. Here we choose Airbnb, install Eslint-config-airbnb(recommended).

NPM Install Eslint-config-airbnb--save-dev

  Eslint-config-airbnb requires support for the following 3 plugins:

NPM Install Eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react--save-dev

Modify. Eslintrc.json to temporarily add the following rules.

{  "Parser": "Babel-eslint",  "Extends": "Airbnb",  "Env": {    "Browser":true,    "Node":true,    "ES6":true  },  "Parseroptions": {    "Ecmaversion": 6,    "SourceType": "Module",    "Ecmafeatures": {      "JSX":true    }  },  "Plugins": [    "React"  ],  "Rules": {    "React/jsx-no-bind": [      "Error",      {        "Ignorerefs":true,        "Allowarrowfunctions":true,        "Allowbind":true      }    ],    "Import/no-extraneous-dependencies": "Off",    "React/jsx-filename-extension": "Off"  }}

After the configuration, re-run, found red a piece (many wrong). Don't worry, we'll change it one step at a-- First modify the Index.js, add /*eslint-disable*/at the head of the file, do not check the index.js. The rest of us will not be changed, you can let the IDE (Webstorm) for us to modify. Select Webstorm's preferences, search for eslint, and apply the rules we created to the project.

Then in the error file, click the red exclamation point, click the first item, you can automatically modify the error.

    • Other common loaders

There are many other common loaders, here is a simple configuration of CSS, the rest of the configuration is not described, please configure your own on-demand. The final webpack.config.js configuration is as follows.

    css-loader: Parsing CSS Code

    style-laoder: Importing compiled CSS styles into HTML

    less-loader: Loading and transferring less files

    raw-loader: Loading file original content (Utf-8 format)

    Url-loader: more for loading pictures

    file-loader: Packaging files

Const PATH= Require (' path ');Const Webpack= Require (' Webpack ');Module.exports={devtool:' Cheap-module-eval-source-map ', entry: [' Babel-polyfill ',    ' React-hot-loader/patch ',    ' webpack-dev-server/client?http://localhost:8080 ',    ' Webpack/hot/only-dev-server ', Path.resolve (__dirname,‘.. /src/index.js '),  ], //Specify the portal file, where the program starts compiling, __dirname the current directory, ... /indicates the previous level of the directory,./Sibling Directoryoutput: {path:path.resolve (__dirname,‘.. /build '),//path to OutputFileName: ' Bundle.js ',//post-packaged files}, module: {rules: [{enforce:' Pre ', test:/\. (JS|JSX) $/, Loader:' Eslint-loader ', exclude:/node_modules/,}, {test:/\. (JS|JSX) $/, Loader:' Babel-loader ',//Loading DeviceExclude:/node_modules/,}, {test:/\.css$/, Loader:' Css-loader ',}, {test:/\.less$/, use: [{loader:' Style-loader ',}, {loader:' Css-loader ',}, {loader:' Less-loader ', Options: {sourcemap:true,} ,}],},],}, plugins: [NewWebpack. Hotmodulereplacementplugin ()  ],};

Construction of react project based on Webpack (II.)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.