Universal-webpack帮助构建同构的Webpack,即在客户端和服务端都可以使用。演示我的演示:universal-webpack+koa+react+webpack。官方的DemoWebpack2目前只支持Webpack2.npminstallwebpack--savenpminstallextract-text-webpack-plugin--save过去我们会创建一个标准的webpack.config.js。此时,我们需要再创建两个配置文件:webpack.config.client.babel.js和webpack.config.client.babel.js。如下:webpack.config.client.babel.jsimport{client}from'universal-webpack/config'importsettingsfrom'./universal-webpack-settings'importconfigurationfrom'./webpack.config'exportdefaultclient(configuration,settings)代替webpack.config.js来完成客户端打包。webpack.config.server.babel.jsimport{server}from'universal-webpack/config'importsettingsfrom'./universal-webpack-settings'importconfigurationfrom'./webpack.config'exportdefaultserver(configuration,settings)universal-webpack-settings.json{"server":{"input":"./source/server.js","output":"./build/server/server.js"}}输出对应文件input对应的文件是Webpack根据webpack.config.server.babel.js中的配置生成的。server.js服务器启动,官方Demo如下://express.jsimportpathfrom'path'importhttpfrom'http'importexpressfrom'express'importhttp_proxyfrom'http-proxy'//react-routerimportroutesfrom'../client/routes.js'//Reduximportstorefrom'../client/store.js'//服务器代码必须导出一个函数//(`parameters`可能包含一些库特定的杂项)导出默认函数(parameters){//创建HTTP服务器constapp=newexpress()constserver=newhttp.Server(app)//服务静态文件app.use(express.static(path.join(__dirname,'..','build/assets')))//对API服务器的代理API调用constproxy=http_proxy.createProxyServer({target:'http://localhost:xxxx'})app.use('/api',(req,res)=>proxy.web(req,res))//React应用程序渲染app.use((req,res)=>{//将当前URL匹配到相应的React页面//(可以使用`react-router`,`redux-router`,`react-router-redux`,etc)react_router_match_url(routes,req.originalUrl).then((error,result)=>{if(error){res.status(500)returnres.send('Servererror')}//RenderReactpageconstpage=redux.provide(result,store)res.status(200)res.send(''+'\n'+ReactDOM.renderToString({page}))})})//启动HTTP服务器server.listen()}但是这个文件并不是真正的入口文件,还需要另外一个文件,我们需要另外一个文件来启动服务start-server.jsvarstartServer=require('universal-webpack/server')varsettings=require('../universal-webpack-settings')//使用`configuration.context`和`configuration.output.path`varconfiguration=require('../webpack.config')startServer(configuration,settings)调用这个入口文件,本质上是调用webpack打包好的server.js。开发环境的启动命令大致如下:webpack-dev-server--hot--inline--config"./webpack.config.client.babel.js"--portXXXX--colors--display-error-details//启动一个webpack-dev-server,真正的DevelopmentServer会从这里请求一些静态文件(eg:boundle.js)。//universal-webpack不会在服务端释放任何资源,所有资源都在客户端)。webpack--watch--config"./webpack.config.server.babel.js"--colors--display-error-details//打包服务器代码nodemon"./source/start-server"--watch"./build/server"启动服务器生产环境。启动命令大致如下:webpack--config"./webpack.config.client.babel.js"--colors--display-error-detailswebpack--config"./webpack.config.server.babel.js"--colors--display-error-detailsnode"./source/start-server"Chunks返回webpack最终输出的文件信息:build/webpack-chunks.json{javascript:{main:`/assets/main.785f110e7775ec8322cf.js`},样式:{main:`/assets/main.785f110e7775ec8322cf.css`}}
