背景
目前在用koa+react+redux搭建一个微信后台,需要用到webpack热加载的方式方便进行开发,同时参考redux官方例子的配置方式,发现
process.env.NODE_ENV
一直是undefined,所以有了这篇文章。
本文主要介绍express以及koa中webpack热加载的实现方式,同时解决process.env.NODE_ENV
传递的问题。
express热加载
通过引入webpack热加载的中间件即可,如下所示
server.js
var webpack = require('webpack') var webpackDevMiddleware = require('webpack-dev-middleware') var webpackHotMiddleware = require('webpack-hot-middleware') var config = require('./webpack.config') var compiler = webpack(config) app.use(webpackDevMiddleware(compiler,{ noInfo: true,publicPath: config.output.publicPath })) app.use(webpackHotMiddleware(compiler))
在webpack.config.js
中引入热加载插件,添加entry入口,以及publicPath
var path = require('path') var webpack = require('webpack') module.exports = { devtool: 'cheap-module-eval-source-map',entry: [ 'webpack-hot-middleware/client','./index' ],output: { path: path.join(__dirname,'dist'),filename: 'bundle.js',publicPath: '/static/' },plugins: [ new webpack.optimize.OccurenceOrderPlugin(),new webpack.HotModuleReplacementPlugin() ],module: { loaders: [ { test: /\.js$/,loaders: [ 'babel' ],exclude: /node_modules/,include: __dirname } ] } }
koa中实现热加载
在koa中如果直接使用express的加载方式,会造成每次触发请求以及返回请求都会重新打包。
解决办法:直接使用koa-webpack-dev-middleware
以及koa-webpack-dev-middleware
,当然阅读这两个中间件源码可以发现它们的加载方式实际上还是和express差不多,只是在执行中间件的时候就已经完成了热加载的过程,如下:
var expressMiddleware = require('webpack-dev-middleware'); function middleware(doIt,req,res) { var originalEnd = res.end; return function (done) { res.end = function () { originalEnd.apply(this,arguments); done(null,0); }; doIt(req,res,function () { done(null,1); }) } } module.exports = function (compiler,option) { var doIt = expressMiddleware(compiler,option); return function*(next) { var ctx = this; var req = this.req; var runNext = yield middleware(doIt,{ end: function (content) { ctx.body = content; },setHeader: function () { ctx.set.apply(ctx,arguments); } }); if (runNext) { yield *next; } }; };
在koa中的使用方式
var webpack = require('webpack'); var webpackDevMiddleware = require('koa-webpack-dev-middleware'); var webpackHotMiddleware = require('koa-webpack-hot-middleware'); var config = require('./webpack.config') var compiler = webpack(config); app.use(webpackDevMiddleware(compiler,publicPath: config.output.publicPath })); app.use(webpackHotMiddleware(compiler));
react中 process.env.NODE_ENV
undefined
这个问题实际上是因为react或者前端本省并不可能获取到
process.env.NODE_ENV
,只能通过后台传递参数到前端才可以。
webpack.config.js(列出部分代码)
var env = process.env.NODE_ENV; var config = { plugins: [ new webpack.optimize.OccurenceOrderPlugin(),new webpack.HotModuleReplacementPlugin(),new webpack.NoErrorsPlugin(),new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(env) }) ],}原文链接:https://www.f2er.com/react/306882.html