Production build with webpack

The last step for our React setup is to have a production build. Until now, we were only using webpack-dev-server, but this naturally includes an unimproved development build. Furthermore, webpack automatically spawns a web server. In a later chapter, we introduce Express.js as our web server so we won't need webpack to host it.

A production bundle does merge all JavaScript files, but also CSS files into two separate files. Those can be used directly in the browser. To bundle CSS files, we will rely on another webpack plugin, called MiniCss:

npm install --save-dev mini-css-extract-plugin

We do not want to change the current webpack.client.config.js file, because it is made for development work. Add this command to the scripts object of your package.json:

"client:build": "webpack --config webpack.client.build.config.js"

This command runs webpack using an individual production webpack config file. Let's create this one. First, clone the original webpack.client.config.js file and rename it webpack.client.build.config.js.

Change the following things in the new file:

  1. The mode needs to be production, not development.
  2. Require the MiniCss plugin:
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  1. Replace the current CSS rule:
{
test: /.css$/,
use: [{ loader: MiniCssExtractPlugin.loader,
options: {
publicPath: '../'
}
}, 'css-loader'],
},

We no longer use the style-loader but instead use the MiniCss plugin. The plugin goes through the complete CSS code, merges it in a separate file, and removes the import statements from the bundle.js we generate in parallel.

  1. Lastly, add the plugin to the plugins at the bottom of the configuration file:
new MiniCssExtractPlugin({
filename: 'bundle.css',
})
  1. Remove the entire devServer property.

When running the new configuration, it won't spawn a server or browser window; it only creates a production JavaScript and CSS bundle, and requires them in our index.html file. According to our webpack.client.build.config.js file, those three files are going to be saved to the dist/client folder.

You can run this command by executing npm run client:build.

Look in the dist/client folder, and you will see three files. You can open the index.html in your browser. Sadly, the images are broken because the image URLs are not right anymore. We accept this for the moment because it will be automatically fixed when we have a working back end.

You are now finished with the basic setup of React.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.20.56