美文网首页
react+router+thunk入坑笔记

react+router+thunk入坑笔记

作者: 马贞晓 | 来源:发表于2017-08-14 15:02 被阅读0次

    安装所需

     npm install -g web pack
     nom install -g babel
    

    以上两个需要全局安装,其他可以使用npm install 或自定义安装

    1.npm install (具体内容如下,可以覆盖package.json),

    {
      "name": "longhu",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "start": "node server.js&webpack --display-error-details -w",
        "dev": "webpack --display-error-details -w"
      },
      "author": "",
      "license": "ISC",
      "devDependencies": {
        "babel-cli": "^6.26.0",
        "babel-core": "^6.26.0",
        "babel-loader": "^7.1.1",
        "babel-preset-es2015": "^6.24.1",
        "babel-preset-react": "^6.24.1",
        "css-loader": "^0.28.4",
        "imagemin-webpack-plugin": "^1.5.0-beta.0",
        "jsx-loader": "^0.13.2",
        "less-loader": "^4.0.5",
        "react": "^15.6.1",
        "react-dom": "^15.6.1",
        "react-hot-loader": "^1.3.1",
        "react-router": "^3.0.5",
        "url-loader": "^0.5.9",
        "webpack": "^3.4.1",
        "webpack-dev-server": "^2.7.1"
      }
    }
    

    2.webpack.config.js配置如下


    • 在实践中发现【publicPath】为chunkFilename的加载路径,如果不指定则默认为根目录下,比较坑爹
    • 【chunkFilename】是用来配合require.ensure的
    • 【require.ensure】 参数1[ ] ,参数2、callback函数,在ballback函数参数里的require用来加载异步js具体看下面main.js内容。
    • 【CommonsChunkPlugin】 是引用的webapck控件自带分割chunk,作用是提取公共组件,防止重复加载。

    var path = require("path");
    var webapck = require("webpack");
    var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin"); //thunk
    var compress = require("webpack/lib/optimize/UglifyJsPlugin"); //压缩
    var DedupePlugin = require("webpack/lib/optimize/DedupePlugin"); //多文件
    var ImageminPlugin = require('imagemin-webpack-plugin').default;//图片压缩
    var config = {
        entry: {
            main: path.join(__dirname, '/content/script/es6/main.js'),
        },
        output: {
            path: path.join(__dirname, '/content/script/dist/script/'),
            filename: "[name].js",
            publicPath:'./content/script/dist/script/',////此处决定了chunkFilename要加载的路径,此处为坑
            chunkFilename: 'chunk-[name].js'//文件拆分chunk
        },
        module: {
            //加载器配置
            loaders: [
                {
                    test: /\.css$/,
                    loader: 'style-loader!css-loader'
                },
                {
                    test: /\.less$/,
                    loader: "style-loader!css-loader!less-loader"
                },
                {
                    test: /\.(png|jpg)$/,
                    loader: 'url-loader',
                    options: {
                        limit: 8192
                      }
                },
                {
                    test: /\.js$/,
                    loaders: ['babel-loader?presets[]=es2015,presets[]=react'],
                    exclude: /node_modules/
                  
                }
            ]
        },
         plugins: [
            new CommonsChunkPlugin({
                name: "chunk"
            }),
              new compress({  //压缩代码
                output: {
                    comments: false,  // remove all comments
                  },
                  compress: {
                    warnings: false
                  }
            }), 
            new DedupePlugin({
                'process.env': {NODE_ENV: '"production"'}
            }),
            new ImageminPlugin({
                disable: process.env.NODE_ENV !== 'production', // Disable during development 
                pngquant: {
                  quality: '95-100'
                }
              })
        ] 
    }
    module.exports = config;
    

    3 .main.js 配置路由,在引入路由时有坑,require('./app').default
    因为默认输入为default所以必须后缀default

    import React from 'react';
    import ReactDOM from 'react-dom';
    import { Router, Route, hashHistory } from "react-router";
    /* import APP from "./app.js"; */
    
    var rootRout = {
      path: '/',
      getComponent: function (next, callback) {
        require.ensure([], function (require) {
          var app =  require('./app.js')
          callback(null, app.default);
        },"app")
      }
    }
    ReactDOM.render((
      <Router history={hashHistory} routes={rootRout}>
      </Router>
    ), document.querySelector("#FloatMenu"))
    
    1. app.js 路由模块
    import React from 'react';
    import ReactDOM from 'react-dom';
    
    class APP extends React.Component{
        constructor(arg){ super(arg)}
        componentWillMount(){
            console.log("======")
        }
        render(){
            var test = "test1"
            return <div>{test}</div>
        }
    
    }
    
    export default APP;
    

    4、webpac-dev-server

    var webpack = require('webpack');
    var WebpackDevServer = require('webpack-dev-server');
    var config = require('./webpack.config');
    new WebpackDevServer(webpack(config), {
        publicPath: config.output.publicPath,
        hot: false,
        historyApiFallback: false
    }).listen(5001, 'localhost', function (err, result) {
        var c = require('child_process');
            c.exec('start http://localhost:5001');
            if (err) {
                console.log(err);
            }
           // console.log('Listening at localhost:5000');
        });
    

    相关文章

      网友评论

          本文标题:react+router+thunk入坑笔记

          本文链接:https://www.haomeiwen.com/subject/opeurxtx.html