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

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.

主站蜘蛛池模板: 郸城县| 寻乌县| 开平市| 林州市| 阿克陶县| 惠州市| 双峰县| 乳山市| 赣州市| 西宁市| 汶川县| 湛江市| 崇信县| 南昌县| 鄄城县| 类乌齐县| 陇南市| 和龙市| 松阳县| 孟津县| 温宿县| 辽源市| 贺州市| 秦安县| 教育| 商河县| 葫芦岛市| 鸡东县| 团风县| 昆山市| 江陵县| 玉溪市| 安达市| 炉霍县| 东宁县| 两当县| 安溪县| 卢湾区| 江阴市| 综艺| 任丘市|