🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# **构建Node + WebPack + React 热加载开发环境** - ## 约定 > 此教程包安装均使用yarn进行安装与管理:[yarn安装方法](https://yarnpkg.com/docs/install/) >如果包只在生成环境下需要请 使用命令 ```yarn add package_name --dev``` - ## 初始化环境 > ![初始化环境](http://p1.bpimg.com/584894/02323e51c370e420.png) - ## 环境构建思路 > 1.npm start 命令执行 2.webpack-dashboard 进行监听webpack的运行状态 3.cross-env进行不同平台下命令兼容执行相关环境变量 4.node调用进行启动express静态容器,解析devServer.js 5.express静态容器,加载webpack服务webpack-dev-middleware 6.express静态容器,加载webpack热加载中间件服务webpack-hot-middleware 7.通过定义公共入口webpack/config.js,根据环境变量加载不同环境下的webpack配置文件 8.必须安装webpack、webpack-dev-server包 - ## 正式构建 - ### 根目录 创建webpack目录 > 目录内新建三个文件:config.js、production.js、development.js - ### 根目录 创建devServer.js - ### 编辑package.json > 新增 scripts项 ,如下: 这里我改变了下webpack-dashboard的socket端口为3032 ~~~ "scripts": { "start": "webpack-dashboard -p 3032 cross-env NODE_ENV=development node devServer.js" }, ~~~ > 现在我们可以到当前目录下npm start了可以看到此界面,当然此时是没有任何信息显示的 空空如也 ![Markdown](http://i1.piimg.com/584894/ed74fe12f51cb482.png) - ### package.json目前内容(把webpack + babel + react 相关的需要用到的包都yarn好了) ~~~ { "name": "NodeCMS", "version": "1.0.0", "description": "NodeCMS is a easy and fast WebSite Manager System", "main": "index.js", "repository": "https://github.com/624508914/node_cms.git", "author": "杨圆建", "license": "MIT", "scripts": { "start": "webpack-dashboard -p 3032 cross-env NODE_ENV=development node devServer.js" }, "devDependencies": { "babel": "^6.5.2", "babel-core": "^6.22.1", "babel-loader": "^6.2.10", "babel-plugin-react-transform": "^2.0.2", "babel-preset-es2015": "^6.22.0", "babel-preset-react": "^6.22.0", "babel-preset-react-hmre": "^1.1.1", "babel-preset-stage-0": "^6.22.0", "cross-env": "^3.1.4", "html-webpack-plugin": "^2.24.1", "react-tools": "^0.13.3", "react-transform": "^0.0.3", "react-transform-catch-errors": "^1.0.2", "react-transform-hmr": "^1.0.4", "redbox-react": "^1.3.3", "webpack": "^2.2.1", "webpack-dashboard": "^0.3.0", "webpack-dev-middleware": "^1.10.0", "webpack-dev-server": "^2.3.0", "webpack-hot-middleware": "^2.16.1" } } ~~~ - ### 编辑devServer.js > 代码如下: ~~~ const express = require('express'); const webpack = require('webpack'); const webpackMiddleware = require('webpack-dev-middleware'); const webpackHotMiddleware = require('webpackHotMiddleware'); const config = require('./webpack/config.js'); const app = express(); // 解析webpack配置 const compiler = webpack(config); const port = process.env.NODE_PORT || 5000; // 定义express的静态文件加载目录 app.use(express.static(__dirname+'/dist')); // 使用webpack中间件 app.use(webpackMiddleware(compiler)); // 使用webpack热加载中间件 app.use(webpackHotMiddleware(compiler)); // 启动express静态服务器 app.listen(port,function(err){ if(err){ console.log(err); return false; } console.log(`Listening at http://localhost:${port}`); }); ~~~ - ### 编辑config.js > 代码如下: ~~~ const path = require('path'); // 获取环境 const ENV = process.env.NODE_ENV || 'development'; // 暴露配置文件 module.exports = require(`./${ENV}.js`); ~~~