webpack2+React使用详解

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

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

    登录后复制

    相信看了本文案例你已经掌握了方法,更多精彩请关注【创想鸟】其它相关文章!

    推荐阅读:

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

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

    以上就是webpack2+React使用详解的详细内容,更多请关注【创想鸟】其它相关文章!

    版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

    发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2771046.html

    (0)
    上一篇 2025年3月8日 12:47:09
    下一篇 2025年3月8日 12:47:16

    AD推荐 黄金广告位招租... 更多推荐

    相关推荐

    • Ajax使用原理分析

      这次给大家带来Ajax使用原理分析,Ajax使用的注意事项有哪些,下面就是实战案例,一起来看一下。 其实AJAX内部实现并不麻烦,主要通过一个叫XMLHttpRequest的对象,而这个对象在现有的浏览器均被支持。 可以说,它是整个AJAX…

      编程技术 2025年3月8日
      200
    • WebStorm ES6怎么使用babel

      这次给大家带来WebStorm ES6怎么使用babel,WebStorm ES6使用babel的注意事项有哪些,下面就是实战案例,一起来看一下。 一、语法支持设置 Preferences > Languages & Fram…

      编程技术 2025年3月8日
      200
    • js链表使用详解

      这次给大家带来js链表使用详解,js链表使用的注意事项有哪些,下面就是实战案例,一起来看一下。 如下所示: Document function Node(v){ this.value=v; this.next=null; } functio…

      编程技术 2025年3月8日
      200
    • vuex+Actions使用详解

      这次给大家带来vuex+Actions使用详解,vuex+Actions使用的注意事项有哪些,下面就是实战案例,一起来看一下。 Action 提交的是 mutation,而不是直接变更状态. Action 是异步的,mutation是同步的…

      编程技术 2025年3月8日
      200
    • JS单双引号嵌套使用详解

      这次给大家带来JS单双引号嵌套使用详解,JS单双引号嵌套使用的注意事项有哪些,下面就是实战案例,一起来看一下。 单引号和双引号之间可以相互嵌套。 1、单引号内只能嵌套双引号。 2、双引号内只能嵌套单引号。 3、如果想在双引号内,再嵌套双引号…

      编程技术 2025年3月8日
      200
    • Vue中v-cloak使用详解

      这次给大家带来Vue中v-cloak使用详解,Vue中v-cloak使用的注意事项有哪些,下面就是实战案例,一起来看一下。 v-cloak 的作用和用法 用法: 这个指令保持在元素上直到关联实例结束编译。和 css 规则如[v-cloak]…

      编程技术 2025年3月8日
      200
    • jQuery EasyUI在WIN中怎么使用

      这次给大家带来jQuery EasyUI在WIN中怎么使用,jQuery EasyUI在WIN中使用的注意事项有哪些,下面就是实战案例,一起来看一下。 管理取派员 function doAdd(){ $(‘#addWindow’).wind…

      编程技术 2025年3月8日
      200
    • jquery插件扩展使用详解

      这次给大家带来jquery插件扩展使用详解,jquery插件扩展使用的注意事项有哪些,下面就是实战案例,一起来看一下。 如下DEMO 展示了为dom扩展一个myshowHtml 的方法 nbsp;html>      你好 (func…

      编程技术 2025年3月8日
      200
    • daterangepicker日历插件使用详解

      这次给大家带来daterangepicker日历插件使用详解,daterangepicker日历插件使用的注意事项有哪些,下面就是实战案例,一起来看一下。 显示具体时间时分秒: timePicker设置为true,//有些资料写的picke…

      编程技术 2025年3月8日
      200
    • 怎么选择使用jQuery版本

      这次给大家带来怎么选择使用jQuery版本,选择使用jQuery版本的注意事项有哪些,下面就是实战案例,一起来看一下。 这篇文章主要给大家介绍了关于如何选择jQuery版本,是1.x? 2.x?还是3.x? 在选择使用jquery之前我们常…

      2025年3月8日 编程技术
      200

    发表回复

    登录后才能评论