Full-Stack React Projects
上QQ阅读APP看书,第一时间看更新

Bundle React app during development

In order to keep the development flow simple, we will initialize Webpack to compile the client-side code when the server is run. In devBundle.js, we will set up a compile method that takes the Express app and configures it to use the Webpack middleware to compile, bundle, and serve code, as well as enable hot reloading in development mode.

mern-simplesetup/server/devBundle.js:

import webpack from 'webpack'
import webpackMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import webpackConfig from './../webpack.config.client.js'

const compile = (app) => {
if(process.env.NODE_ENV == "development"){
const compiler = webpack(webpackConfig)
const middleware = webpackMiddleware(compiler, {
publicPath: webpackConfig.output.publicPath
})
app.use(middleware)
app.use(webpackHotMiddleware(compiler))
}
}

export default {
compile
}

We will call this compile method in server.js by adding the following lines while in development mode.

mern-simplesetup/server/server.js:

import devBundle from './devBundle'
const app = express()
devBundle.compile(app)

These two highlighted lines are only meant for development mode and should be commented out when building the application code for production. In development mode, when these lines are executed, Webpack will compile and bundle the React code to place it in dist/bundle.js.