- Full-Stack React Projects
- Shama Hoque
- 237字
- 2021-06-25 21:45:12
Loading Webpack middleware for development
During development, when we run the server, the Express app should load the Webpack middleware relevant to the frontend with respect to the configuration set for the client-side code, so that the frontend and backend development workflow is integrated. To enable this, we will use the devBundle.js file discussed in Chapter 2, Preparing the Development Environment, to set up a compile method that takes the Express app and configures it to use the Webpack middleware. The devBundle.js in the server folder will be as follows.
mern-skeleton/server/devBundle.js:
import config from './../config/config'
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(config.env === "development"){
const compiler = webpack(webpackConfig)
const middleware = webpackMiddleware(compiler, {
publicPath: webpackConfig.output.publicPath
})
app.use(middleware)
app.use(webpackHotMiddleware(compiler))
}
}
export default {
compile
}
Then, import and call this compile method in express.js by adding the following highlighted lines only while developing.
mern-skeleton/server/express.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 code for production. This code will import the middleware and the Webpack configuration before initiating Webpack to compile and bundle the client-side code when the Express app runs in development mode. The bundled code will be placed in the dist folder.