官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 遵化市| 万源市| 祁连县| 桃园市| 会泽县| 云南省| 金平| 华蓥市| 偏关县| 泸水县| 遂川县| 喀什市| 烟台市| 武邑县| 城口县| 乌审旗| 竹北市| 政和县| 仲巴县| 凌源市| 枣阳市| 墨脱县| 元朗区| 霍林郭勒市| 裕民县| 买车| 体育| 红桥区| 宁城县| 黎城县| 吴桥县| 贞丰县| 华坪县| 乌苏市| 康乐县| 阿瓦提县| 徐汇区| 浦江县| 仙游县| 新密市| 镇江市|