美文网首页
React系列学习笔记:2.Express配置

React系列学习笔记:2.Express配置

作者: Moon_Yue | 来源:发表于2016-04-06 16:30 被阅读1471次

    前言

    本节主要利用express搭配webpack作为开发服务器,并利用babel的插件,实现热替换功能,本节使用的包列表:

    • express: node的服务器框架

    • webpack-dev-middleware:webpack实时监控编译的中间件

    • webpack-hot-middleware:hot替换中间件

    • babel-plugin-react-transformbabel插件

    • react-transform-hmr:react支持热替换

        npm install --save-dev webpack-dev-middleware
        npm install --save-dev webpack-hot-middleware
        npm install --save-dev babel-plugin-react-transform
        npm install --save-dev react-transform-hmr
      

    添加的文件

    关babel,node,server更详细的配置可以参考babel官方提供的方法example-node-server

    • .babelrcnode启动时采用babel的编译配置
    • scr/server.js服务器文件
    • config/appConfig.js应用配置文件

    新的目录结构

    |-react-redux-example/
        ...
        |-config/
            |-appConfig.js
        |-src/
            |-app.js
            |-server.js
        ...
        |-.babelrc
    

    更改配置

    webpack.dev.js

    react-transform可以直接写在.babelrc文件中的,但是我们以后会加入其他插件(加入后会与其他插件冲突),所以这里写在webpack.dev.js中,新的配置如下:

    var path = require('path')
    var webpack = require('webpack')
    
    var projectRootPath = path.resolve(__dirname,'..')
    
    var config = {
      entry: [
        path.resolve(projectRootPath,'src/app.js')
      ],
      output:{
        path: path.resolve(projectRootPath,'public','assets'),
        filename: 'bundle.js',
        publicPath: '/assets/'
      },
      module:{
        loaders:[
          {
            test:/\.js$/,
            exclude:/node_modules/,
            loader:'babel-loader',
            query:{
              presets:['react','es2015'],
              plugins:[]
            }
          }
        ]
      },
      plugins:[
        new webpack.DefinePlugin({
          "process.env":{
            NODE_ENV:JSON.stringify(process.env.NODE_ENV)
          }
         })
      ]
    }
    
    //添加hotreplace支持
    if (process.env.NODE_ENV !== 'production') {
      config.devtool = 'eval';
      config.entry.unshift ('webpack-hot-middleware/client')
      config.plugins.unshift(new webpack.HotModuleReplacementPlugin());
    
      // Note: enabling React Transform and React Transform HMR:
      config.module.loaders[0].query.plugins.push([
        'react-transform', {
          transforms: [{
            transform : 'react-transform-hmr',
            imports   : ['react'],
            locals    : ['module']
          }]
        }
      ]);
    }
    
    module.exports=config;
    

    config/appConfig.js

    应用基本的配置参数

    const environment = {
      development: {
        isProduction: false
      },
      production: {
        isProduction: true
      }
    }[process.env.NODE_ENV || 'development'];
    
    module.exports = Object.assign({
      host: process.env.HOST || 'localhost',
      port: process.env.PORT||3000,
      apiHost: process.env.APIHOST || 'localhost',
      apiPort: process.env.APIPORT ||3030,
    }, environment);
    

    src/server.js

    import path from 'path'
    import webpack from 'webpack'
    import express from 'express'
    import appConfig from '../config/appConfig'
    
    const app = express()
    
    //webpack中间件配置,包括hotReplace
    if(!appConfig.isProduction){
      const wpConfig = require('../config/webpack.dev.js');
      const compiler = webpack(wpConfig)
    
      const webpackMiddleware = require("webpack-dev-middleware");
      const webpackHotMiddleware =require('webpack-hot-middleware');
    
      app.use(webpackMiddleware(compiler,{
        publicPath:wpConfig.output.publicPath,
        noInfo:true,
        stats:{colors:true}
      }))
      app.use(webpackHotMiddleware(compiler))
    }
    
    //静态文件服务
    app.use(express.static(path.join(__dirname,'../public')))
    
    app.use('*',(req,res) =>{
      res.sendFile(path.join(__dirname,'../public/index.html'))
    })
    
    if (appConfig.port){
      app.listen(appConfig.port,appConfig.host,(err) =>{
        if (err){
          console.log(err)
        }else{
          console.info('server is running at %d',appConfig.port)
        }
      })
    }else{
      console.error('No port is set')
    }
    

    src/app.js

    热替换不能对根结点,所以这里写了一个简单的测试组件

    import React from 'react'
    import ReactDOM from 'react-dom'
    
    class Hello extends React.Component {
      render(){
        return(
          <h1>Hello333</h1>
        )
      }
    }
    
    ReactDOM.render(<Hello />,document.getElementById('app'))
    

    build

    npm run dev
    

    运行后打开浏览器访问http://localhost:3000,针对chrome浏览器打开“开发者工具console选项卡”看见如图效果后,说明热替换启用


    现在你可以改变Hello组件中的<h1>hello</h1>的值,不用刷新浏览器也会同时更新。

    NEXT

    react路由设置及第一个组件编写

    相关文章

      网友评论

          本文标题:React系列学习笔记:2.Express配置

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