After we successfully installed Webpack and configured the custom packaging command, before using Webpack in the project, of course, we need to modify the basic configuration, and install some plug-ins for file processing. This article mainly describes the common simple configuration, and other configurations and plug-in installation see the official webPack documentation. webpack.docschina.org/concepts/

1. Modify basic configurations

When using webpack, it will find the default entry (SRC /index.js in the root path) according to the configuration parameters set in the webpack.config.js file in the root path of the project. And output to the default exit (dist/main.js generated in the root path).

In the formal project, if the entry and exit paths need to be modified:

// Write in webpack.config.js in the root path
const path = require("path")

module.exports = {
    entry: "Entry file path".output: { 
        path: "Exit folder path"
        filename:"Exit file name"}}Copy the code

We divide the project development process into different environments: development environment, online environment.

The generated files vary depending on the packaging requirements, and you need to add properties to package.json.

{"mode": "production"/"production"}Copy the code

2. Common plug-in configuration

2.1 Automatic generation of HTML files — htMl-webpack-plugin

Webpack will only pack JS files at the exit, but also need to manually copy the HTML file to the exit folder, and manually reference the JS, htMl-webpack-plugin is used to solve this problem. After configuration is complete, the HTML files can be copied to the export folder when packaging and the packaged JS files can be automatically imported.

  1. Download the plugin
 yarn add html-webpack-plugin  -D
Copy the code
  1. Configure in webpack.config.js


// Introduce a plug-in that automatically generates HTML
const HtmlWebpackPlugin = require('html-webpack-plugin') 

module.exports = {
    plugins: [
        new HtmlWebpackPlugin({
            // Use this as a base to generate a packaged HTML file
            template: './public/index.html'}})]Copy the code

2.2 Handling CSS Files — CSS-loader & style-loader

Webpack can only recognize JS files, not CSS files, but CSS files are necessary for project writing, so CSS-loader & style-loader came into being, which can package CSS files into JS files. Render the page style by generating the style tag in the head tag.

  1. Download the plugin
yarn add css-loader style-loader -D
Copy the code
  1. Configure in webpack.config.js


// Introduce a plug-in that automatically generates HTML
const HtmlWebpackPlugin = require('html-webpack-plugin') 

module.exports = {
     module: { // How to handle different module files in a project
        rules: [ / / rules
          {
            test: /\.css$/.// Matches all CSS files
            // use array to run from right to left
            // Use csS-loader to enable WebPack to recognize the contents of CSS files and package them
            // Use style-loader to insert the CSS into the DOM
            use: [ "style-loader"."css-loader"}]}}Copy the code

Although this method can help WebPack identify the packaged CSS files, but ultimately the CSS files are packaged into JS, which is not readable. Is there any way to package the CSS files we need to package into a separate CSS file?

Working with CSS files (extracting CSS into separate files) — Mini-CSS-extract-plugin

1. Download the plug-in

yarn add mini-css-extract-plugin -D 
Copy the code
  1. Configure in webpack.config.js
// Introduce a plugin that generates CSS files
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  plugins: [new MiniCssExtractPlugin()],
  module: {
    rules: [{test: /.css$/i.// Matches all CSS files/ Use CSS-loader to enable WebPack to recognize the contents of CSS files and package them// Generate a separate CSS file in the export folder with the mini-css-extract-plugin
        use: [MiniCssExtractPlugin.loader, "css-loader"],},],},};Copy the code

2.3 Processing less Files — less-loader

  1. Import the less files that need to be packaged into main.js
Import "file path/filename. Less"Copy the code
  1. Downloading dependency packages
Yarn add less [email protected] -dCopy the code
  1. Configure in webpack.config.js

module: {
  rules: [{test: /.less$/.// Matches the.less end file
        // Use less loader, let Webpack process less files, built-in less module, translate less code into CSS code
        use: [ "style-loader"."css-loader".'less-loader']]}}Copy the code

2.4 Processing image files

Webpack5 built-in processing solution, only need to fill in the configuration

Configure in webpack.config.js

Module: {rules: [{test: /. (PNG | JPG | | GIF jpeg) $/ I / / matching image file type: 'asset' // Automatically selects between exporting a data URI and a single file // If less than 8KB, convert it to a data URI(image is converted into base64 string and wrapped into JS) // If greater than 8KB, Copy files directly to dist (because base64 increases volume by 30%)}]}Copy the code

2.5 Processing font files

The same as image processing method, Webpack5 built-in processing scheme, just need to fill in the configuration

Configure in webpack.config.js

{ 
    test: /\.(eot|svg|ttf|woff|woff2)$/,
    type: 'asset/resource'.// Copy files directly as static resources
    generator: {
    	filename: 'font/[name].[hash:6][ext]' // Place it in the dist/font folder}}Copy the code

2.6 Handling higher version JS syntax – Babel compiler

When we write js code will be used to es6 and higher version of the latest in grammar to simplify the code, but some browsers can’t high resolution version correct grammar, causing us to write the code in the browser can’t display effect, this is what we call compatibility problems, in order to solve this problem, we use the Babel to the compiler. The older JS syntax is degraded while using Webpack to package the code, greatly improving compatibility.

  1. Installing dependency packages
yarn add babel-loader @babel/core @babel/preset-env -D 
Copy the code
  1. Configure in webpack.config.js
module: {
    rules: [{test: /.js$/.// Matches the js ending file
            exclude: /(node_modules|bower_components)/.// Do not convert the js in these two folders
            use: { 
                loader: 'babel-loader'.// Use loader - handle
                options: {
                    presets: ['@babel/preset-env'] // Default: transcoding rules (with bable development environment originally preset)}}}]}Copy the code

Note: Proper use of the various plug-ins provided in the official documentation can solve many of the problems we have encountered with them!

3, start local server — webpack-dev-server

Webpack-dev-server is a small static Node.js Express server that uses the webpack-dev-middleware middleware to provide Web services for resource files generated through webpack packaging. Why use it?

3.1 the advantages

When you run the yarn serve command to package the project, webpack the entire project from 0. If the code changes little, it is still packaged frequently for debugging, which greatly affects the development efficiency.

If you use a local server, when the code changes, the server will automatically replace the changed parts and refresh the browser to show the effect of the code changes. In the actual work, it can greatly improve the development efficiency and avoid spending time on useless repeated packaging, saving time.

3.2 Usage

  1. The installation
yarn add webpack-dev-server --dev
Copy the code
  1. Set common configuration items
module.exports = {
    devServer: {
      port: 3000.// Port number (default port 8080 if not set)
      open: true // Automatically opens the browser after startup}}Copy the code

For more server configuration items, see the official documentation. Webpack.docschina.org/configurati…