0

0

webpack2+React使用详解

php中世界最好的语言

php中世界最好的语言

发布时间:2018-04-18 10:46:59

|

1913人浏览过

|

来源于php中文网

原创

这次给大家带来webpack2+React使用详解,webpack2+React使用的注意事项有哪些,下面就是实战案例,一起来看一下。

1.涉及到的插件需要npm install安装;
2.html-webpack-plugin创建服务于 webpack bundle 的 HTML 文件;
3.clean-webpack-plugin清除dist目录重复的文件;
4.extract-text-webpack-plugin分离css文件。

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.新建.babelrc

{
 "presets": ['es2015','react','stage-3']
}

5.index.html



 
  
  React Project
 
 
  

6.package.json

npm install 或 yarn -> 安装模块,npm run build -> 打包,npm 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:入口文件

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(, $('#content')[0]);
// render(, $('#content')[0]);

8.templateIndex.html

打包后的模板index文件,插件html-webpack-plugin的template指定的目录。



 
  
  Template Index html
 
 
  

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 
  • name:{item.name},tel:{item.tel}
  • }) } render(){ let btnStyle = { border: '1px solid #ccc', background:'#fff', color: '#a106ce' } return ( /* 注释 */


    Hello { this.props.textCont}!

    {this.state.content ? 'initial value' : 'later value'}

    { /* 标签里面的注释外面要用花括号 */ }

    {this.state.value}

    lalala

      { this.renderArr() }

    ) } } Demo1.propTypes = { title: React.PropTypes.string.isRequired } Demo1.defaultProps = { textCont: 'React' } class DemoChild extends React.Component { constructor(props) { super(props); } render(){ return (

    我是子组件{this.props.children}

    ) } }

    demo1.css

    ul {
      list-style: none;
      padding: 0;
      margin:0;
      display: flex;
    }
    .btn:focus {
      outline: none;
    }

    demo2.js:父子组件生命周期

    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 (
        

    姓名:{this.props.myName}

    问候:{this.state.stateName}

    年龄:{this.props.age}

    性别:{this.props.sex}

    父元素计数是:{this.state.count}

    aspx1财付通支付接口源码
    aspx1财付通支付接口源码

    本支付接口的特点,主要是用xml文件来记录订单详情和支付详情。代码比较简单,只要将里面的商户号、商户key换成你自己的,将回调url换成你的网站,就可以使用了。通过这个实例也可以很好的了解一般在线支付接口的基本工作原理。其中的pay.config文件记录的是支付详情,order.config是订单详情

    下载

    ) } } 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(

    子元素计数是:{this.props.count1}

    ) } }

    demo2.css

    .colorStyle {
      color: #0f0;
    }

    相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

    推荐阅读:

    Vue Router+Vuex实现后退状态保存

    BootStrap实现上传文件时显示进度

    相关专题

    更多
    C++ 高级模板编程与元编程
    C++ 高级模板编程与元编程

    本专题深入讲解 C++ 中的高级模板编程与元编程技术,涵盖模板特化、SFINAE、模板递归、类型萃取、编译时常量与计算、C++17 的折叠表达式与变长模板参数等。通过多个实际示例,帮助开发者掌握 如何利用 C++ 模板机制编写高效、可扩展的通用代码,并提升代码的灵活性与性能。

    10

    2026.01.23

    php远程文件教程合集
    php远程文件教程合集

    本专题整合了php远程文件相关教程,阅读专题下面的文章了解更多详细内容。

    29

    2026.01.22

    PHP后端开发相关内容汇总
    PHP后端开发相关内容汇总

    本专题整合了PHP后端开发相关内容,阅读专题下面的文章了解更多详细内容。

    21

    2026.01.22

    php会话教程合集
    php会话教程合集

    本专题整合了php会话教程相关合集,阅读专题下面的文章了解更多详细内容。

    21

    2026.01.22

    宝塔PHP8.4相关教程汇总
    宝塔PHP8.4相关教程汇总

    本专题整合了宝塔PHP8.4相关教程,阅读专题下面的文章了解更多详细内容。

    13

    2026.01.22

    PHP特殊符号教程合集
    PHP特殊符号教程合集

    本专题整合了PHP特殊符号相关处理方法,阅读专题下面的文章了解更多详细内容。

    11

    2026.01.22

    PHP探针相关教程合集
    PHP探针相关教程合集

    本专题整合了PHP探针相关教程,阅读专题下面的文章了解更多详细内容。

    8

    2026.01.22

    菜鸟裹裹入口以及教程汇总
    菜鸟裹裹入口以及教程汇总

    本专题整合了菜鸟裹裹入口地址及教程分享,阅读专题下面的文章了解更多详细内容。

    55

    2026.01.22

    Golang 性能分析与pprof调优实战
    Golang 性能分析与pprof调优实战

    本专题系统讲解 Golang 应用的性能分析与调优方法,重点覆盖 pprof 的使用方式,包括 CPU、内存、阻塞与 goroutine 分析,火焰图解读,常见性能瓶颈定位思路,以及在真实项目中进行针对性优化的实践技巧。通过案例讲解,帮助开发者掌握 用数据驱动的方式持续提升 Go 程序性能与稳定性。

    9

    2026.01.22

    热门下载

    更多
    网站特效
    /
    网站源码
    /
    网站素材
    /
    前端模板

    精品课程

    更多
    相关推荐
    /
    热门推荐
    /
    最新课程
    React 教程
    React 教程

    共58课时 | 4万人学习

    国外Web开发全栈课程全集
    国外Web开发全栈课程全集

    共12课时 | 1.0万人学习

    React核心原理新老生命周期精讲
    React核心原理新老生命周期精讲

    共12课时 | 1万人学习

    关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
    php中文网:公益在线php培训,帮助PHP学习者快速成长!
    关注服务号 技术交流群
    PHP中文网订阅号
    每天精选资源文章推送

    Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号