webpack2+React使用详解

轻雪吖_9946

轻雪吖_9946

2018-04-18

1973人浏览

原创

这次给大家带来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

html>

 
  <meta>
  <title>React Project</title>
 
 
  <p></p>
  <script></script>
 

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

8.templateIndex.html

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

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 
  • 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 (
        <p>
          </p><p>姓名:{this.props.myName}</p>
          <p>问候:{this.state.stateName}</p>
          <p>年龄:{this.props.age}</p><div class="aritcle_card flexRow artxards">
    											<div class="artcardd flexRow">
    												<a class="aritcle_card_img" rel="nofollow" href="/xiazai/learn/7239" title="Web前端Promise教程从入门到精通课件"><img
    														src="https://img.php.cn/upload/webcode/000/000/164/623042ba405ab871.jpg" alt="Web前端Promise教程从入门到精通课件" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
    												<div class="aritcle_card_info flexColumn">
    													<a rel="nofollow" href="/xiazai/learn/7239" title="Web前端Promise教程从入门到精通课件" class="overflowclass">Web前端Promise教程从入门到精通课件</a>
    													<p class="overflowclass">Web前端Promise教程从入门到精通课件</p>
    												</div>
    												<a rel="nofollow" href="/xiazai/learn/7239" title="Web前端Promise教程从入门到精通课件" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
    												</a>
    											</div>
    										</div>
          <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;
    }

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

    推荐阅读:

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

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

    相关文章

    PHP速学视频免费教程(入门到精通)
    PHP速学视频免费教程(入门到精通)

    PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

    下载

    相关标签:

    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

    相关专题

    更多
    Go-Zero API开发使用教程
    Go-Zero API开发使用教程

    本专题聚焦Go-Zero的API开发,拆解.api描述文件的语法结构、路由与分组定义、参数绑定与校验规则,说明统一响应体、JWT鉴权、跨域与接口文档生成的落地方式,并给出网关聚合与接口测试的实践建议。

    2026.11.12

    140

    15

    Go-Zero安装与goctl环境配置教程
    Go-Zero安装与goctl环境配置教程

    本专题围绕Go-Zero的安装与工具链配置展开,讲清Go版本要求、goctl安装方式、代理镜像、protoc依赖与环境变量设置,说明多版本共存、升级回退与CI流水线安装的做法,并整理安装阶段的常见报错与验证步骤。

    2026.11.12

    100

    15

    Go-Zero零基础入门教程
    Go-Zero零基础入门教程

    本专题整理Go-Zero的入门知识,从框架定位、环境准备到跑通第一个API服务,讲清目录分层、配置加载、日志与中间件的基本用法,并对比Gin、Kratos的差异,帮助Go开发者建立整体认知,判断它是否适合当前项目。

    2026.11.12

    80

    15

    Postman身份认证怎么配置
    Postman身份认证怎么配置

    本专题从实际API接口调试场景出发,讲解Postman身份认证的完整配置流程,包括常见认证协议介绍、授权参数设置、访问令牌填写、OAuth 2.0授权及认证失败排查,帮助用户正确完成接口授权与访问验证。

    2026.11.06

    160

    12

    Postman请求头Headers怎么设置
    Postman请求头Headers怎么设置

    围绕Postman HTTP请求头配置展开,讲解Headers选项的具体使用方式,包括Key和Value参数填写、请求头信息添加、常见Header字段设置及请求头修改方法,帮助用户解决接口调试过程中遇到的请求头配置问题。

    2026.11.06

    140

    13

    Postman接口请求发送教程
    Postman接口请求发送教程

    详细介绍Postman接口请求的创建与发送方法,涵盖GET和POST请求、URL配置、请求参数、Headers请求头、Body请求体设置以及响应结果查看,帮助用户掌握Postman接口请求的完整操作流程。

    2026.11.06

    120

    10

    DBeaver怎么导入数据
    DBeaver怎么导入数据

    DBeaver数据导入专题,整理Excel、CSV、SQL、TXT等常见文件的数据导入方法,涵盖目标数据库选择、数据表创建、字段映射、数据类型设置及导入参数配置等操作,帮助用户将本地文件中的数据写入数据库,并了解批量导入、重复数据处理和导入失败等常见问题的解决方法。

    2026.11.05

    120

    12

    DBeaver安全防护教程大全
    DBeaver安全防护教程大全

    DBeaver安全防护专题,围绕数据库连接安全、账号密码保护和访问权限管理展开,整理SSL/TLS加密连接、SSH隧道、数据库凭据保存及证书验证等配置方法,同时介绍敏感信息保护、远程连接风险和高权限账号使用等注意事项,帮助用户提高数据库日常管理的安全性。

    2026.11.05

    100

    12

    DBeaver连接创建与配置教程
    DBeaver连接创建与配置教程

    本专题聚焦DBeaver数据库连接配置与管理,覆盖从新建连接、选择数据库类型到填写连接参数和验证连接的完整流程。针对MySQL、PostgreSQL、SQL Server等常见数据库,整理相应的连接设置方法,并提供驱动缺失、认证失败和连接异常等问题的排查方向。

    2026.11.04

    120

    16

    热门下载

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

    精品课程

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