前文回顾

前一篇文章主要介绍介绍在react中引入redux,本篇主要介绍在react中引入router

添加引用

# router

npm install --save react-router react-router-dom

# 异步加载

npm install --save react-loadable

添加文件

routers文件夹下添index.js

import React from 'react';
import Loadable from 'react-loadable';
import { BrowserRouter as Router, Route, Switch, withRouter } from 'react-router-dom';

const loading = () => {
    return <div>loading...</div>
}

const AsyncHome = Loadable({
    loader: () => import('../pages/home'),
    loading: loading
})


const AsyncError = Loadable({
    loader: () => import('../pages/error'),
    loading: loading
})

const App = (props) => (
    <Switch>
        <Route path="/" exact  component={AsyncHome}/>
        <Route path="/home" component={AsyncHome}></Route>
        <Route path="/error" component={AsyncError}></Route>

    </Switch>

)

export default withRouter(App);

修改index.js

import React from 'react'
import { render } from 'react-dom'
import { createStore, applyMiddleware } from 'redux'
import { Provider } from 'react-redux'
import { createLogger } from 'redux-logger'
import thunk from 'redux-thunk'
import reducer from './reducers/index'

import { BrowserRouter, Router } from 'react-router-dom';
import App from './routers/index'

const middleware = [thunk];
if (process.env.NODE_ENV !== 'production') {
  middleware.push(createLogger());
}

const store = createStore(
  reducer,
  applyMiddleware(...middleware)
)

render(
  <Provider store={store}>
    <BrowserRouter forceRefresh={true} >
      <App />
    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
)

webpack.config.js

var path = require('path');

const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const HtmlWepackPlugin = require('html-webpack-plugin')

const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  entry: path.resolve(__dirname, 'app/index.js'), //入口文件
  output: {
    path: path.resolve(__dirname, 'build'),       //输出文件夹
    filename: 'bundle.js'             //输入文件名
  },
  mode: 'development',                //none, development 或 production(默认)
  module: {
    rules: [
      {
        test: /\.jsx?$/,                          //使用babel-loader解析js文件和jsx文件
        exclude: /node_modules/,
        loader: 'babel-loader'
      }, {
        test: /.css$/,                            // 解析css文件的后缀
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              // you can specify a publicPath here
              // by default it use publicPath in webpackOptions.output
              publicPath: '../'
            }
          },
          "css-loader"
        ]
      }, {
        test: /\.(gif|jpg|png|jpeg)$/,           // 解析图片
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 3400,
              name: '[name].[ext]'
            }
          }],
        exclude: /node_modules/
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin({ cleanAfterEveryBuildPatterns: ["./build"] }),                     // 清除文件
    new HtmlWepackPlugin({
      template: path.resolve(__dirname, './public/index.html'),  // 固定配置
      filename: 'index.html'                    // 生成对应的文件名
    }),
    new MiniCssExtractPlugin({
      filename: "css/[name].[hash].css",
      chunkFilename: "css/[name].[hash].css"
    })
  ],
  devtool: 'eval-source-map',
  devServer: {
    historyApiFallback: true,
    progress: true,                               //显示进度条
    // quiet: true,                               // 把替换输出给清除掉。
    overlay: {
      errors: true,
      warnings: true
    },
    contentBase: path.join(__dirname, './build'),
    host: 'localhost',                            //域名
    port: '8092',                                 //端口
    hot: true,                                    //热更新
    open: true
  },
}
02-11 21:27