react mobx webpack 使用案例

1、package.json:

{
  "name": "wtest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node server.js",
    "build": "NODE_ENV=production&&npm run output",
    "output": "webpack --config webpack.build.js",
    "test": "node ./dist/test.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "autoprefixer-loader": "^3.2.0",
    "babel-core": "^6.23.1",
    "babel-loader": "^6.3.2",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-es2016": "^6.22.0",
    "babel-preset-es2017": "^6.22.0",
    "babel-preset-react": "^6.23.0",
    "babel-preset-stage-0": "^6.22.0",
    "copy-webpack-plugin": "^4.0.1",
    "css-loader": "^0.26.2",
    "extract-text-webpack-plugin": "^2.0.0",
    "file-loader": "^0.10.1",
    "html-webpack-plugin": "^2.28.0",
    "mobx": "^3.1.2",
    "mobx-react": "^4.1.1",
    "node-sass": "^4.5.0",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-hot-loader": "^1.3.1",
    "react-router": "^3.0.2",
    "reload": "^1.1.1",
    "sass-loader": "^6.0.2",
    "style-loader": "^0.13.2",
    "uglifyjs-webpack-plugin": "^0.3.0",
    "webpack": "^2.2.1",
    "webpack-del-plugin": "^0.0.1",
    "webpack-dev-middleware": "^1.10.1",
    "webpack-dev-server": "^2.4.1",
    "webpack-hot-middleware": "^2.17.1",
    "webpack-spritesmith": "^0.3.1",
    "webpack-uglify-js-plugin": "^1.1.9"
  }
}

2、webpack:

const webpack = require(‘webpack‘);
const webpackUglifyJsPlugin = require(‘webpack-uglify-js-plugin‘);
const path = require(‘path‘);
const ExtractTextPlugin = require(‘extract-text-webpack-plugin‘);
const HtmlWebpackPlugin = require(‘html-webpack-plugin‘);

const config = {
    entry: [
        "webpack-hot-middleware/client?reload=true",
        // 这里是你的入口文件
        "./index.js",
    ],
    output: { //输出目录
        publicPath: "",
        path: __dirname,
        filename: ‘bundle.js‘,
    },
    module: {
        rules: [{
            test: /\.jsx?$/,
            use: [‘react-hot-loader‘, {
                loader: ‘babel-loader‘,
                options: {
                    presets: [‘es2015‘, ‘es2016‘, ‘es2017‘, ‘stage-0‘, ‘react‘],  //babel presets ,首先需要react解析react然后再es语法编译成js
                    plugins: [‘transform-decorators-legacy‘]
                }
            }],
            exclude: /node_modules/
        }, {
            test: /\.scss$/,
            use: ExtractTextPlugin.extract({
                fallback: "style-loader",
                loader: "css-loader!autoprefixer-loader?{browsers:[‘last 6 Chrome versions‘, ‘last 3 Safari versions‘, ‘iOS >= 5‘, ‘Android >= 4.0‘]}!sass-loader",
            }),
        }, {
            test: /\.png$/,
            use: {
                loader: ‘file-loader‘,
                options: {
                    name: ‘../img/[name].[ext]‘
                }
            }
        }]
    },
    plugins: [
        new webpack.optimize.OccurrenceOrderPlugin(),
        new webpack.HotModuleReplacementPlugin(), //热编译开启
        new webpack.NoEmitOnErrorsPlugin(),
        new ExtractTextPlugin(‘css/style.css‘)
        /*new HtmlWebpackPlugin({
            title: ‘index‘,
            hash:true,
            template: ‘index.ejs‘, // Load a custom template (ejs by default see the FAQ for details)
        })*/
    ]
};
module.exports = config;

3、server.js:

var webpack = require(‘webpack‘),
    webpackDevMiddleware = require(‘webpack-dev-middleware‘),
    webpackHotMiddleware = require(‘webpack-hot-middleware‘),
    config = require("./webpack.start.js"),
    express = require(‘express‘),
    app = express(),
    compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath,
    noInfo: true,
    stats: {
        colors: true,
        progress: true
    }
}));
app.use(webpackHotMiddleware(compiler, { //中间件实现热刷新
    noInfo: true,
    publicPath: config.output.publicPath
}));

app.get(‘*‘, function(req, res) {
    var fileName = req.url;
    console.log(fileName);
    if (fileName == ‘/‘) {
        res.sendFile(__dirname + ‘/index.html‘);
    }else{
        res.sendFile(__dirname + fileName);
    }
});
app.listen(8087,‘0.0.0.0‘);  //node 构建server

3、store:

import { observer } from "mobx-react";
import { observable, action, computed ,autorun} from "mobx";
export default class NewStore {
    @observable inputValue1; //注册监听的数据
    @observable inputValue2;
    @observable childValue;
    constructor() {
        this.inputValue1=0;
        this.inputValue2=0;//初始化数据的值
        this.fullValue=0;
        this.childValue=0;
    }
    @action changeValue(s,e){ //当促发action的时候,改变对应的数据
        let tar=e.currentTarget;
        let val=Math.abs(tar.value);
        if(tar.name==‘val1‘){
            this.inputValue1=val;
        }else if(tar.name==‘val2‘){
            this.inputValue2=val;
        }
    }

    @computed get sum(){  //computed 是自动监听登记的数据,如果对应数据有改变就自动执行该函数,然后返回数据给接收的接口
        this.fullValue=this.inputValue1+this.inputValue2;
        console.log(this.fullValue)
        return this.fullValue;
    }
    @action childEvent(){
        this.childValue=this.childValue+3;
    }
}
import TestStore from  ‘./test.js‘;
import NextStore from "./next.js";
import NewStore from "./new.js";
import FormStore from "./form.js";
import MenuStore from "./menu.js";
import NumChange from "./comm/numChange.js"

export default {
	testStore:new TestStore(),
	nextStore:new NextStore(),
	newStore:new NewStore(),
	formStore:new FormStore(),
	menuStore:new MenuStore(),
	numChange:new NumChange()
}

4、index.js:

import "./js/auto_rem.js";
import "./css/style.scss";
import React from "react";
import { render } from "react-dom";
import { observable, computed, autorun } from "mobx";
import { Provider } from ‘mobx-react‘;
import { Router, Route, hashHistory ,browserHistory} from ‘react-router‘;
import Test from "./src/components/test.js";
import Next from "./src/components/next.js";
import New from "./src/components/new.js";
import Forms from "./src/components/form.js";
import Menu from "./src/components/menu.js";
import store from "./src/store/store.js";

const routes = (
  <Route component={App}>
     <Route path="/" component={Menu}/>
     <Route path="/menu" component={Menu}/>
     <Route path="/form" component={Forms}/>
     <Route path="/new" component={New}/>
     <Route path="/test" component={Test}/>
     <Route path="/next" component={Next}/>
  </Route>
);
class App extends React.Component {
    render() {
        return (
             <Provider {...store}>  //注入所有的store
                 <Router history={hashHistory} >
                      {routes}
                 </Router>
             </Provider>
         )
    }
}

render( < App />, document.getElementById(‘app‘));

  

4、view:

import {observer,inject} from "mobx-react";
import {observable,action,computed,autorun} from "mobx";

import React,{Component} from "react";
import {render} from "react-dom";
import Child from "./comm/child.js";
@inject([‘newStore‘]) @observer //引入需要的store,然后组件就可以在props中访问
export default class New extends Component{
  constructor(props) {
    super(props);
    this.store=this.props.newStore; //访问注入的store
    this.changeValue=this.store.changeValue.bind(this.store,event) //访问mobx中的事件,store中的事件
  }
  render(){
    return(
        <div>
          <input type=‘tel‘ name=‘val1‘ onKeyUp={this.changeValue}/>+
          <input type=‘tel‘ name=‘val2‘ onKeyUp={this.changeValue}/>=
          <span>{this.store.sum}</span>
          <Child/>
        </div>
      )
  }
}

  

时间: 2024-11-06 20:18:15

react mobx webpack 使用案例的相关文章

React +ES6 +Webpack入门

React +ES6 +Webpack入门 React已成为前端当下最热门的前端框架之一 , 其虚拟DOM和组件化开发让前端开发更富灵活性,而Webpack凭借它异步加载和可分离打包等优秀的特性,更为React的开发提供了便利.其优秀的特性不再赘述.本文将详细的记录react babel webpack的环境搭建,以及搭建的过程中遇到的一些坑. 一.新建React项目 1.如图为新建react项目结构,其中 entry.js放置react入口代码,index.js放置react组件代码,asse

reactjs学习一(环境搭配react+es6+webpack热部署)

reactjs学习一(环境搭配react+es6+webpack热部署) reactjs今年在前端圈里很火,用了三四个月,感觉确实很适合前端开发人员使用,值得深入一下,所以这里记录一下我简单的学习过程,首先是react的环境,由于现在react的新版本已经很稳定了,所以推荐使用es6+webpack来搭建开发环境. 首先,安装nodejs,略过,安装gitbrach,略过,直接搜索到相对应软件的官网,下载最新正式版本的软件,然后就下一步下一步完成安装就可以了,很简单的过程,但是不容忽略,如有问题

React+ES6+Webpack深入浅出

React已成为前端当下最热门的前端框架之一 , 其虚拟DOM和组件化开发让前端开发更富灵活性,而Webpack凭借它异步加载和可分离打包等优秀的特性,更为React的开发提供了便利.其优秀的特性不再赘述.本文将详细的记录react babel webpack的环境搭建,以及搭建的过程中遇到的一些坑. 一.新建React项目 1.如图为新建react项目结构,其中 entry.js放置react入口代码,index.js放置react组件代码,assets文件是webpack打包之后生成文件的存

spring + spring mvc + mybatis + react + reflux + webpack Web工程例子

最近写了个Java Web工程demo,使用maven构建: 后端使用spring + spring mvc + mybatis: 前端使用react + reflux + webpack,使用ES6语法:顺带用了下jquery,bootstrap,echarts等插件,写了两个小demo 初版,还需不断完善. 先来个整体感觉吧, 贴几张图: 后端,熟悉的人自然熟悉: 前端, 有没感觉前端的写法越来越像后端了,对于我这种业余前端选手来说,挺喜欢这种目录结构和语法的,哈哈哈: 运行效果: 后端说明

React使用——webpack

新建目录: demo(文件夹) --views(文件夹) --demo.html --app(文件夹) --components(文件夹) --demo.jsx --js(文件夹) --demo_1.js --demo_2.js --css(文件夹) --demo.css --main.js(入口文件) 编辑内容: 1.demo.html的内容为: <!DOCTYPE html> <html lang="en"> <head> <meta ch

webpack开发案例(三)

基于webpack开发案例(二) 项目结构 案例一(实现根组件的头部和底部样式) App.vue <!--以后项目的根组件--> <template> <div> <!--1.0利用mint-ui中的header组件实现整个系统的头部--> <mt-header fixed title="hello"></mt-header> <!--2.0利用vue-router的<router-view>&l

webpack开发案例(四)

基于webpack开发案例(三) 案例一(新闻列表的实现) 目录结构 步骤一:创建newslist.vue文件 <template> <div id="tml"> <!--使用mui框架,实现新闻资讯列表样式--> <ul class="mui-table-view"> <li v-for="item in list" class="mui-table-view-cell mui-m

react+mobx+antd按需加载 出现Support for the experimental syntax &#39;decorators-legacy&#39; isn&#39;t currently enabled

baidu上面的说法大多是在 项目的package.json 中添加decorators-legacy 因为引入了antd的按需加载 所以只需要在config-overrides.js中添加addDecoratorsLegacy() const { override, fixBabelImports,addDecoratorsLegacy } = require('customize-cra'); module.exports = override( fixBabelImports('impor

前端框架及项目面试-聚焦Vue、React、Webpack

第1章 课程导学介绍课程制作的背景和课程主要内容. 第2章 课程介绍先出几道面试真题,引导思考.带着问题来继续学习,效果更好. 第3章 Vue 使用Vue 是前端面试必考内容,首先要保证自己要会使用 Vue .本章讲解 Vue 基本使用.组件使用.高级特性和 Vuex Vue-router ,这些部分的知识点和面试题. 第4章 Vue 原理要保证自己的面试竞争力,必须掌握 Vue 原理,前端高级面试或者大厂面试中常考.本章讲解虚拟DOM,diff 算法,响应式,模板编译,组件渲染等 Vue 原理