从零开始搭建React全家桶环境

博客地址:地址

Github项目地址: 地址

创建项目

 $ mkdir example
 $ cd example
 $ npm init -y复制代码

创建目录结构

├── config              // webpack配置文件目录
├── package.json        
├── server              // 开启本地node服务文件,包括热更新等
└── src                 // 源文件目录复制代码

安装Webpack

$ npm i --save-dev webpack复制代码

编写Webpack配置文件

在config目录下新建文件:

$ cd config
$ touch webpack.config.dev.js
$ touch webpack.config.pro.js复制代码

我们先来写开发环境下的 webpack.config.dev.js

const path = require('path')
const webpack = require('webpack')
​
// 先定义一些路径
// 配置文件夹路径
const CONFIG_PATH = path.resolve(__dirname)
// 源码文件夹路径
const APP_PATH = path.resolve(CONFIG_PATH, '../src')
// 应用入口文件
const APP_FILE = path.resolve(APP_PATH, 'index.js')
// 打包目录文件夹路径
const BUILD_PATH = path.resolve(ROOT_PATH, '../dist')
​
module.exports = {
  // 入口
  entry: APP_FILE,
  // 输出
  output: {
    // 告诉Webpack结果存储在哪里
    path: BUILD_PATH,
    // 打包后的文件名
    filename: 'bundle.js',
    //模板、样式、脚本、图片等资源对应的server上的路径
    publicPath: "/assets/",
  }
}复制代码

一个最简单的webpack配置文件已完成

安装Babel

我们使用ES6来编写代码,所以需要安装ES6的babel-preset

$ npm i --save-dev babel-cli babel-loader babel-preset-es2015 babel-preset-react babel-preset-stage-0复制代码

同时修改webpack配置文件,在module.exports增加:

module: {
  rules: [{
    test: /\.js$/,
    exclude: /node_modules/,
    loader: "babel-loader"
  }]
}复制代码

在根目录添加babelrc文件

cd /path/to/example
touch .babelrc复制代码

修改.babelrc

{
  "env": {
    "development": {
      "presets" : ["es2015", "stage-0", "react"],
    },
    "production": {
      "presets" : [["es2015", { "modules": false, "loose": true }], "stage-0", "react"],]
    }
  }
}复制代码

安装其他Loader

  • css-loader

  • style-loader

  • postcss-loader

  • less-loader

  • file-loader

  • url-loader

  • autoprefixer

npm i --save-dev css-loader style-loader file-loader less less-loader postcss-loader url-loader autoprefixer复制代码

同时修改webpack配置文件,修改module.exports下的module.rules:

rules: [
  {
    test: /\.js$/,
    exclude: /node_modules/,
    loader: "babel-loader"
  },
  {
    test: /\.css$/,
    use: [
      'style-loader',
      'css-loader',
      {
        loader: 'postcss-loader',
        options: {
          plugins: (loader) => [
            require('autoprefixer')()
          ]
        }
      }
    ]
  },
  {
    test: /\.less$/,
    use: [
      'style-loader',
      'css-loader',
      {
        loader: 'postcss-loader',
        options: {
          plugins: (loader) => [
            require('autoprefixer')()
          ]
        }
      },
      'less-loader'
    ]
  },
  {
    test: /\.(eot|woff|ttf|woff2|svg|gif)(\?|$)/,
    loader: 'file-loader?name=[hash].[ext]'
  },
  {
    test: /\.(png|jpg)$/,
    loader: 'url-loader?limit=1200&name=[hash].[ext]'
  }
]复制代码

本地node服务

在server下新建server.js和index.html:

$ cd server
$ touch server.js
$ touch index.html复制代码

安装server服务依赖

$ npm i --save express复制代码

修改server.js文件

const app = new (require('express'))()
// 本地预览代码的端口
const port = 3003
​
app.get('*', function(req, res) {
  res.sendFile(__dirname + '/index.html')
})
​
app.listen(port, function(error) {
  if (error) {
    /*eslint no-console: 0*/
    console.error(error)
  } else {
    /*eslint no-console: 0*/
    console.info("==> ? Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port)
  }
})复制代码

最简单的本地预览服务已经完成

热更新

我们使用react-hot-loader来做热更新,webpack-dev-middlewarewebpack-hot-middlewaref来实时刷新页面

安装依赖

$ npm i --save-dev react-hot-loader webpack-dev-middleware webpack-hot-middleware复制代码

编写index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, viewport-fit=contain"/>
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title></title>
</head>
<body ontouchstart="">
  <div id="app"></div>
  <script src="/assets/bundle.js"></script>
</body>
</html>
​复制代码

修改server.js

const webpack = require('webpack')
const webpackDevMiddleware = require('webpack-dev-middleware')
const webpackHotMiddleware = require('webpack-hot-middleware')
const config = require('../config/webpack.config.dev.js')
const app = new (require('express'))()
// 本地预览代码的端口
const port = 3003
​
const compiler = webpack(config)
​
app.use(webpackDevMiddleware(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath,
  stats: {
    colors: true
  }
}))
​
app.use(webpackHotMiddleware(compiler))
​
app.get('*', function(req, res) {
  res.sendFile(__dirname + '/index.html')
})
​
app.listen(port, function(error) {
  if (error) {
    /*eslint no-console: 0*/
    console.error(error)
  } else {
    /*eslint no-console: 0*/
    console.info("==> ?  Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port)
  }
})复制代码

修改webpack.config.dev.js的module.exports 的entry

entry: [
    'react-hot-loader/patch',
    // 这里reload=true的意思是,如果碰到不能hot reload的情况,就整页刷新。
    'webpack-hot-middleware/client?reload=true',
    APP_FILE
],复制代码

在module.exports添加:

plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('development') //定义编译环境
      }
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin()
],复制代码

在babelrc文件中添加preset

"plugins" : ["react-hot-loader/babel"]复制代码

.babelrc

最终代码:

{
  "env": {
    "development": {
      "presets" : ["es2015", "stage-0", "react"],
      "plugins" : ["react-hot-loader/babel"]
    },
    "production": {
      "presets" : [["es2015", { "modules": false, "loose": true }], "stage-0", "react"],
    }
  }
}
​复制代码

webpack.config.dev.js

最终代码:

/**
 * @author Chan Zewail
 * ###### Thu Jan 25 19:28:40 CST 2018
 */
const path = require('path')
const webpack = require('webpack')
​
// 先定义一些路径
// 配置文件夹路径
const CONFIG_PATH = path.resolve(__dirname)
// 源码文件夹路径
const APP_PATH = path.resolve(CONFIG_PATH, '../src')
// 应用入口文件
const APP_FILE = path.resolve(APP_PATH, 'index.js')
// 打包目录文件夹路径
const BUILD_PATH = path.resolve(ROOT_PATH, '../dist')
​
module.exports = {
  entry: [
    'react-hot-loader/patch',
    // 这里reload=true的意思是,如果碰到不能hot reload的情况,就整页刷新。
    'webpack-hot-middleware/client?reload=true',
    APP_FILE
  ],
  output: {
    // 告诉Webpack结果存储在哪里
    path: BUILD_PATH,
    // 打包后的文件名
    filename: 'bundle.js',
    //模板、样式、脚本、图片等资源对应的server上的路径
    publicPath: "/assets/",
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: "babel-loader"
      },
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader',
          {
            loader: 'postcss-loader',
            options: {
              plugins: (loader) => [
                require('autoprefixer')()
              ]
            }
          }
        ]
      },
      {
        test: /\.less$/,
        use: [
          'style-loader',
          'css-loader',
          {
            loader: 'postcss-loader',
            options: {
              plugins: (loader) => [
                require('autoprefixer')()
              ]
            }
          },
          'less-loader'
        ]
      },
      {
        test: /\.(eot|woff|ttf|woff2|svg|gif)(\?|$)/,
        loader: 'file-loader?name=[hash].[ext]'
      },
      {
        test: /\.(png|jpg)$/,
        loader: 'url-loader?limit=1200&name=[hash].[ext]'
      }
    ]
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('development') //定义编译环境
      }
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin()
  ],
  resolve: {
    //后缀名自动补全
    extensions: ['.js', '.jsx', '.less', '.scss', '.css'], 
    // 根路径别名
    alias: {
      '@': `${APP_PATH}/`,
    },
    modules: [
      'node_modules',
      'src',
    ]
  }
}
​复制代码

npm脚本命令

安装一些工具依赖

npm i --save-dev copyfiles clean-webpack-plugin复制代码

在package.json中添加:

"scripts": {
    "dev": "node server/server.js",
    "start": "npm run dev",
    "copy": "copyfiles -f ./server/index.html ./dist",
    "build": "npm run copy && webpack --config config/webpack.config.pro.js"
},复制代码

开始编写项目代码

安装react

npm i --save react react-dom复制代码
入口文件
$ cd src
# 入口文件
$ touch index.js
# 应用文件
$ touch App.js复制代码

编写index.js

import React from 'react'
import ReactDOM from 'react-dom'
import { AppContainer } from 'react-hot-loader'
// 应用文件
import App from './App'
​
ReactDOM.render(
  <AppContainer>
    <App/>
  </AppContainer>
  , document.getElementById('app'))
​
// 热更新
if (module.hot) {
  module.hot.accept('./App', () => {
    const NextApp = require('./App').default
    ReactDOM.render(
      <AppContainer>
        <NextApp/>
      </AppContainer>,
      document.getElementById('app')
    )
  })
}复制代码

全家桶

  • react

  • react-dom

  • react-router

  • redux

  • redux-saga

  • redux-persist

  • history

  • redux-logger

  • react-router-redux

npm i --save react-router redux redux saga reux-persist history redux-logger react-router-redux复制代码

编写configureStore生成store,

$ cd src
$ mkdir store
$ touch index.js复制代码
/**
 * @author Chan Zewail
 * ###### Thu Jan 25 19:28:40 CST 2018
 */
import { createStore, applyMiddleware, compose } from 'redux'
import { persistStore } from 'redux-persist'
import reducers from '@/reducers'
import createHistory from 'history/createHashHistory'
import { routerMiddleware } from 'react-router-redux'
import createSagaMiddleware from 'redux-saga'
import sagas from '@/sagas'
import logger from 'redux-logger'
​
// 创建history
export const history = createHistory()
​
//创建saga中间件
const sagaMiddleware = createSagaMiddleware()
​
// 需要调用的中间件
const middleWares = [
  sagaMiddleware,
  routerMiddleware(history),
  logger
]
​
// 生成store
const store = createStore(reducers, undefined, compose(
  applyMiddleware(...middleWares),
))
​
// 将store数据保存到缓存
const persistor = persistStore(store, null)
​
// 生成最终的store函数
export default function configureStore(){
  // 运行saga
  sagaMiddleware.run(sagas)
  return { persistor, store }
}
​
export function getPersistor() {
  return persistor
}
​复制代码

编写reducer

$ cd src
$ mkdir reducers
$ touch index.js复制代码
/**
 * @author Chan Zewail
 * ###### Thu Jan 25 19:28:40 CST 2018
 */
import { routerReducer } from 'react-router-redux'
import { persistCombineReducers, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage'
// import xxxReducer from './xxx'
​
// redux-persist 配置
export const config = {
  key: 'root',
  storage,
  debug: true,
  // 将对应reducer保存到本地缓存的白名单
  whitelist: [
    'routing',
  ]
}
​
​
// 合并reducer
export default persistCombineReducers(config, {
  routing: routerReducer, // 默认引入路由reducer
  // xxx: xxxReducer,
})
​复制代码

编写saga

$ cd src
$ mkdir sagas
$ touch index.js复制代码
/**
 * @author Chan Zewail
 * ###### Thu Jan 25 19:28:40 CST 2018
 */
import { fork, all } from 'redux-saga/effects'
// import xxxSagaFlow from './xxxFlow'
​
// 根saga
export default function* rootSaga () {
  yield all([
    // fork(xxxSagaFlow)
  ])
}
​复制代码

App.js

/**
 * @author Chan Zewail
 * ###### Thu Jan 25 19:28:40 CST 2018
 */
import React from 'react'
import { Provider } from 'react-redux'
import { history } from '@/store'
import { ConnectedRouter } from 'react-router-redux'
import { PersistGate } from 'redux-persist/es/integration/react'
import { Redirect } from 'react-router-dom'
​
// persister 缓存恢复前调用的方法
const onBeforeLift = () => {
  // console.log('before action')
}
​
class App extends React.Component {
  constructor(props) {
    super(props)
  }
​
  render() {
    const { persistor, store } = this.props.stores
    // 主页面
    return (
      <Provider store={store}>
        <PersistGate loading={<div/>} onBeforeLift={onBeforeLift} persistor={persistor}>
          <ConnectedRouter history={history}>
            // switch and route
          </ConnectedRouter>
        </PersistGate>
      </Provider>
    )
  }
}
​
export default App
​复制代码

修改 index.js并添加获取store方法,然后传递到App的props(热更新store)

index.js

/**
 * @author Chan Zewail
 * ###### Thu Jan 25 19:28:40 CST 2018
 */
import React from 'react'
import ReactDOM from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import configureStore from '@/store'
// 主页面
import App from './App'export const stores = configureStore()
​
ReactDOM.render(
  <AppContainer>
    <App stores={stores}/>
  </AppContainer>
  , document.getElementById('app'))
​
// 热更新
if (module.hot) {
  module.hot.accept('./App', () => {
    const NextApp = require('./App').default
    ReactDOM.render(
      <AppContainer>
        <NextApp stores={stores}/>
      </AppContainer>,
      document.getElementById('app')
    )
  })
}
​复制代码

最后

最基础的react全家桶已搭建完毕,其他功能可逐渐加入并个性化定制

最终代码:github.com/czewail/zew…

使用问题可在Issues提出

欢迎Start


转载于:https://juejin.im/post/5a715fadf265da3e5661d667

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值