iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > VUE >webpack2+React的示例分析
  • 242
分享到

webpack2+React的示例分析

2024-04-02 19:04:59 242人浏览 泡泡鱼
摘要

这篇文章主要为大家展示了“webpack2+React的示例分析”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“WEBpack2+React的示例分析”这篇文章吧

这篇文章主要为大家展示了“webpack2+React的示例分析”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“WEBpack2+React的示例分析”这篇文章吧。

1.目录结构

源文件在src目录下,打包后的文件在dist目录下。

webpack2+React的示例分析

2.webpack.config.js

说明:

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

<!doctype html>
<html lang="en">
 <head>
  <meta charset="utf-8">
  <title>React Project</title>
 </head>
 <body>
  <div id="content"></div>

  <script src="app.bundle.js"></script>
 </body>
</html>

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 title="这是提示" />, $('#content')[0]);
// render(<Demo2 myName="园中桥" sex="female"/>, $('#content')[0]);

8.templateIndex.html

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

<!doctype html>
<html lang="en">
 <head>
  <meta charset="utf-8">
  <title>Template Index html</title>
 </head>
 <body>
  <div id="content"></div>
 </body>
</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 <li key={index}>name:{item.name},tel:{item.tel}</li>
      })
  }

  render(){
    let btnStyle = {
      border: '1px solid #ccc',
      background:'#fff',
      color: '#a106ce'
    }
    return (
        
        <div>
          <button style={btnStyle} className="btn" type="button" onClick={()=>this.handleClick()}>change state</button><br/>
          <p title={this.props.title} style={{ color:'#A349A4' }}>Hello { this.props.textCont}!</p>
          <p>{this.state.content ? 'initial value' : 'later value'}</p>
          {  }
          <input type="text" value={this.state.value} ref="myInput" onChange={this.handleChange.bind(this)} /> 
          <h5>{this.state.value}</h5>
          <DemoChild><p>lalala</p></DemoChild>
          <ul>
            { this.renderArr() }
          </ul>
        </div>
      )
  }
}

Demo1.propTypes = {
  title: React.PropTypes.string.isRequired
}
Demo1.defaultProps = {
  textCont: 'React'
}

class DemoChild extends React.Component {
  constructor(props) {
    super(props);
  }

  render(){
    return (
        <div>我是子组件{this.props.children}</div>
      )
  }
}

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 (
    <div>
      <p className="colorStyle">姓名:{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 onClick={ this.doUpdateCount.bind(this) } style={{ padding: 5,backgroundColor: '#ccc' }}>点我开始计数</button>
      <SubMyPropType count1={this.state.count} />
    </div>
    )
  }
}

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

以上是“webpack2+React的示例分析”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注编程网VUE频道!

--结束END--

本文标题: webpack2+React的示例分析

本文链接: https://www.lsjlt.com/news/79757.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • webpack2+React的示例分析
    这篇文章主要为大家展示了“webpack2+React的示例分析”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“webpack2+React的示例分析”这篇文章吧...
    99+
    2022-10-19
  • angular+webpack2的示例分析
    这篇文章主要介绍了angular+webpack2的示例分析,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。webpack出了中文版以后,对于...
    99+
    2022-10-19
  • webpack2.x中vue2.x多页面站点的示例分析
    这篇文章将为大家详细讲解有关webpack2.x中vue2.x多页面站点的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。具体如下:vue的多页面依旧使用vue-c...
    99+
    2022-10-19
  • react hooks的示例分析
    这篇文章将为大家详细讲解有关react hooks的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。React在16.8版本正式发布了Hooks。关注了很久,最近正...
    99+
    2022-10-19
  • React中ref的示例分析
    这篇文章给大家分享的是有关React中ref的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。为了摆脱繁琐的Dom操作, React提倡组件化, 组件内部用数据来驱动视图的...
    99+
    2022-10-19
  • Javascript之React的示例分析
    这篇文章主要介绍Javascript之React的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!前言React核心的单向数据流、一切皆数据的state、不会改变的props,...
    99+
    2022-10-19
  • react组件拆分的示例分析
    这篇文章将为大家详细讲解有关react组件拆分的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。前言:React 是一个用于构建用户界面的 JAVASCRIPT 库。主要用于构建UI,很多人认为 R...
    99+
    2023-06-06
  • React之组件的示例分析
    小编给大家分享一下React之组件的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!一、分割 render 函数当一个组件...
    99+
    2022-10-19
  • React中的Virtual DOM示例分析
    本篇内容主要讲解“React中的Virtual DOM示例分析”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“React中的Virtual DOM示例分析”吧!这是Choero...
    99+
    2023-06-29
  • React中JSX与react事件的示例分析
    小编给大家分享一下React中JSX与react事件的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!1、JSX1.1、表...
    99+
    2022-10-19
  • redux、react-redux、redux-saga的示例分析
    小编给大家分享一下redux、react-redux、redux-saga的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧...
    99+
    2022-10-19
  • React碰到v-if的示例分析
    这篇文章将为大家详细讲解有关React碰到v-if的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。代码:import React from&n...
    99+
    2022-10-19
  • React中setState源码的示例分析
    这篇文章将为大家详细讲解有关React中setState源码的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。React作为一门前端框架,虽然只是focus在MVV...
    99+
    2022-10-19
  • React高阶组件的示例分析
    这篇文章将为大家详细讲解有关React高阶组件的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。高阶组件的定义HoC 不属于 React 的 API,它是一种实现模...
    99+
    2022-10-19
  • React事件处理的示例分析
    小编给大家分享一下React事件处理的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!React的事件处理和DOM的事件处...
    99+
    2022-10-19
  • redux以及react-redux的示例分析
    这篇文章给大家分享的是有关redux以及react-redux的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。redux 简介随着 JavaScript 单页应用开发日趋...
    99+
    2022-10-19
  • React中this绑定的示例分析
    这篇文章主要介绍了React中this绑定的示例分析,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。 我们在re...
    99+
    2022-10-19
  • react中useEffect闭包的示例分析
    这篇文章主要介绍react中useEffect闭包的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!问题代码看一段因为useEffect导致的闭包问题代码const btn = u...
    99+
    2023-06-15
  • React中ref属性的示例分析
    这篇文章主要介绍了React中ref属性的示例分析,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。概述首先,Refs 和 ref 是两个概念,Refs 是 React 提供的可...
    99+
    2023-06-15
  • React中生命周期的示例分析
    这篇文章将为大家详细讲解有关React中生命周期的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。React的生命周期两张图带你理解 React的生命周期React的生命周期(旧)class&nbs...
    99+
    2023-06-20
软考高级职称资格查询
推荐阅读
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作