This time I will bring you a detailed explanation of the use of webpack2 React. What are the precautions when using webpack2 React? The following is a practical case, let’s take a look.
1. The plug-ins involved need to be installed by npm install;
2.html-webpack-plugin creates HTML files that serve the webpack bundle;
3.clean-webpack-plugin clears duplicate files in the dist directory;
4.extract-text-webpack-plugin separates css files.
var path = require('path'); var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var CleanWebpackPlugin = require('clean-webpack-plugin'); var ExtractTextPlugin = require("extract-text-webpack-plugin"); var UglifyJsPlugin = webpack.optimize.UglifyJsPlugin; var config = { context: path.resolve(dirname, './src'), entry: { app: './main.js' }, output: { path: path.resolve(dirname, './dist'), filename: '[name].bundle.js' }, devtool: 'cheap-module-eval-source-map', module: { rules: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: ["css-loader","postcss-loader"] }) }, { test: /\.less$/, use: ["style-loader","css-loader","less-loader"] }, { test: /\.(png|jpg)$/, loader: 'url-loader', options: { limit: 8129 } } ] }, devServer:{ historyApiFallback: true, host:'0.0.0.0', hot: true, //HMR模式 inline: true,//实时刷新 port: 8181 // 修改端口,一般默认是8080 }, resolve: { extensions: ['.js', '.jsx', '.css'], modules: [path.resolve(dirname, './src'), 'node_modules'] }, plugins: [ new webpack.HotModuleReplacementPlugin(), new UglifyJsPlugin({ sourceMap: true }), new webpack.LoaderOptionsPlugin({ minimize: true, debug: true }), new HtmlWebpackPlugin({ template:'./templateIndex.html' }), new ExtractTextPlugin({ filename: '[name].[hash].css', disable: false, allChunks: true, }), new CleanWebpackPlugin(['dist']) ], } module.exports = config; // webpack里面配置的bundle.js需要手动打包才会变化,目录可以由自己指定; // webpack-dev-server自动检测变化自动打包的是开发环境下的bundle.js,打包路径由contentBase决定,两个文件是不一样的.
3.postcss.config.js(Autoprefixer)
module.exports = { plugins: { 'autoprefixer': {browsers: 'last 5 version'} } } // 兼容最新的5个浏览器版本
4.New .babelrc
{ "presets": ['es2015','react','stage-3'] }
5.index.html
nbsp;html> <meta> <title>React Project</title> <p></p> <script></script>
6.package.json
npm install or yarn -> install the module, npm run build -> package, npm start -> start localhost:8181
{ "name": "reactproject", "version": "1.0.0", "description": "", "main": "index.js", "dependencies": { "jquery": "^3.1.1", "react": "^15.3.2" }, "devDependencies": { "autoprefixer": "^7.1.2", "babel-core": "^6.14.0", "babel-loader": "^6.2.5", "babel-plugin-syntax-async-functions": "^6.13.0", "babel-plugin-transform-async-to-generator": "^6.16.0", "babel-preset-es2015": "^6.14.0", "babel-preset-react": "^6.11.1", "babel-preset-stage-3": "^6.17.0", "bootstrap": "^4.0.0-alpha.2", "clean-webpack-plugin": "^0.1.16", "css-loader": "^0.25.0", "extract-text-webpack-plugin": "^3.0.0-rc.2", "file-loader": "^0.9.0", "html-webpack-plugin": "^2.29.0", "jshint": "^2.9.3", "jshint-loader": "^0.8.3", "json-loader": "^0.5.4", "less": "^2.7.1", "less-loader": "^2.2.3", "moment": "^2.15.1", "node-sass": "^3.10.0", "postcss-loader": "^2.0.6", "react-bootstrap": "^0.30.5", "react-dom": "^15.3.2", "sass-loader": "^4.0.2", "style-loader": "^0.13.1", "url-loader": "^0.5.7", "webpack": "^3.3.0", "webpack-dev-server": "^2.5.1" }, "scripts": { "start": "webpack-dev-server --hot --inline --progress --colors --content-base .", "build": "webpack --progress --colors" }, "keywords": [ "reactcode" ], "author": "xhh", "license": "ISC" }
7.main.js:Entry file
import React from 'react' import { render } from 'react-dom'; import $ from 'jquery'; import Demo1 from './js/demo1.js'; // import Demo2 from './js/demo2.js'; render(<demo1></demo1>, $('#content')[0]); // render(<demo2></demo2>, $('#content')[0]);
8.templateIndex.html
The packaged template index file, the directory specified by the template of the plug-in html-webpack-plugin.
nbsp;html> <meta> <title>Template Index html</title> <p></p>
9.demo
demo1.js
import React from 'react'; import '../css/demo1.css'; const arr = [ { name:'name1', tel:'12343456783' }, { name:'name2', tel:'12343456784' }, { name:'name3', tel:'12343456785' } ]; export default class Demo1 extends React.Component { constructor(props) { super(props); this.state = { content: true, value: 'inputText' }; } handleClick(){ this.setState({ content: !this.state.content }) // this.refs.myInput.focus(); } handleChange(event) { this.setState({value: event.target.value}); } renderArr() { return arr.map((item,index)=>{ return
Hello { this.props.textCont}!
{this.state.content ? 'initial value' : 'later value'}
{ /* 标签里面的注释外面要用花括号 */ }{this.state.value}
lalala
-
{ this.renderArr() }
我是子组件{this.props.children}
) } }demo1.css
ul { list-style: none; padding: 0; margin:0; display: flex; } .btn:focus { outline: none; }
demo2.js: Parent-child componentLife cycle
import React, { Component, PropTypes } from 'react'; import '../css/demo2.css'; export default class Demo2 extends Component { constructor(props){ super(props); this.state = { stateName: this.props.myName + ',你好', count: 0, } console.log('init-constructor'); } static get defaultProps() { return { myName: "xhh", age: 25 } } doUpdateCount(){ this.setState({ count: this.state.count+1 }) } componentWillMount() { console.log('componentWillMount'); } componentDidMount() { console.log('componentDidMount') } componentWillReceiveProps(nextProps){ console.log('componentWillReceiveProps') } shouldComponentUpdate(nextProps, nextState){ console.log('shouldComponentUpdate'); // return nextProps.id !== this.props.id; if(nextState.count > 10) return false; return true; } componentWillUpdate(nextProps,nextState){ console.log('componentWillUpdate'); } componentDidUpdate(prevProps, prevState){ console.log('componentDidUpdate'); } componentWillUnmount(){ console.log('componentWillUnmount'); } render(){ console.log('render'); return ( <p> </p><p>姓名:{this.props.myName}</p> <p>问候:{this.state.stateName}</p> <p>年龄:{this.props.age}</p> <p>性别:{this.props.sex}</p> <p>父元素计数是:{this.state.count}</p> <button>点我开始计数</button> <submyproptype></submyproptype> ) } } Demo2.propTypes = { myName: PropTypes.string, age: PropTypes.number, sex: PropTypes.string.isRequired } class SubMyPropType extends Component { componentWillMount() { console.log('subMyPropType-componentWillMount'); } componentDidMount() { console.log('subMyPropType-componentDidMount') } componentWillReceiveProps(nextProps){ console.log('subMyPropType-componentWillReceiveProps') } shouldComponentUpdate(nextProps, nextState){ console.log('subMyPropType-shouldComponentUpdate'); if(nextProps.count1 > 5) return false; return true; } componentWillUpdate(nextProps, nextState){ console.log('subMyPropType-componentWillUpdate'); } componentDidUpdate(prevProps, prevState){ console.log('subMyPropType-componentDidUpdate'); } componentWillUnmount(){ console.log('subMyPropType-componentWillUnmount'); } render(){ console.log('subMyPropType-render'); return( <p>子元素计数是:{this.props.count1}</p> ) } }
demo2.css
.colorStyle { color: #0f0; }
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
Vue Router Vuex implements back state saving
BootStrap implements displaying progress when uploading files
The above is the detailed content of Detailed explanation of webpack2+React usage. For more information, please follow other related articles on the PHP Chinese website!

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.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.


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

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.

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

SublimeText3 Chinese version
Chinese version, very easy to use

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor
