[TOC]

Use of the Webpack packaging tool

Preface:

Webpack is the most popular packaging tool at the front end. In order to save the time of learning Webpack, I will introduce the use of Webpack in the form of a case. After all, learning Webpack is to know how to use it Tools are vscode

Basic knowledge of

npm

Once you install the Node environment, NPM is installed automatically

cnpm

After in the node, and there is a global NPM command can be used, but the NPM download various packet to the default server abroad, download speed big affected, sometimes can also lead to some environmental problems, so we can choose from domestic server download package, thanks to the willing to share taobao team, provides the domestic developers NPM the images of all kinds of packages

Run the following command to install taobao NPM package download tool

npm i -g cnpm --registry=https://registry.npm.taobao.org
Copy the code

When downloading the package, use the following command, using the keyword CNPM, as in

cnpm i  vue --save
Copy the code

Note: some warning messages may appear during the process of downloading packages using CNPM, which does not affect the actual use of packages. However, if you want to view the dependencies of packages after installation, you may not find them. What is dependency? We’ll talk about that later

Therefore, it is recommended to use a package management tool to set which server NPM downloads packages from

nrm

Run the following command to install the NRM

npm install nrm -g
Copy the code
  1. View the list of available servers NRM ls

  2. View the server NRM Current in use

  3. Switch to the specified server NRM use The server name

  4. Speed command

    nrm test

    NRM test Specifies the server name

From the above, the optimal use of NPM is as follows:

Install NRM and set the server for downloading NPM packages to Taobao

Use of NPM command line tools

  1. Download packages (local installation) The downloaded packages are placed in the node_modules folder of the current project! NPM install Package name NPM install package name @version number

    Abbreviations:

    NPM I Package name NPM I package name @Version number

    NPM install Package name Package name 1 Package name 2

  2. Uninstallation package NPM uninstall Specifies the package name

  3. Global installation

    When using a package that provides a global command, the package needs to be installed globally!

    NPM install package name -g NPM install package name –global

Why use Webpack?

What common static resources are referenced in a web page?

  • JS
  • Js.jsx.coffee. ts (TypeScript C#)
  • CSS
  • .css .less .sass .scss
  • Images
  • .jpg .png .gif .bmp .svg
  • Font files
  • .svg .ttf .eot .woff .woff2
  • Template file
  • .ejs.jade. vue [This is the recommended way to define components in webpack]

What would be the problem if we introduced these files in the traditional way?

  1. Web pages load slowly because we make a lot of secondary requests;
  2. There are intricate dependencies to deal with

Let’s begin our first packing case

1. Build a directory structure

Note:

  • Directory do not appear Chinese file name, the outermost file name do not use Webpack, I above is to serve as a negative lesson
  • Where main.js is the import file and bundle.js is the export file, which will be discussed later

Set the server of NPM download package as Taobao

Open in the client

Execute command:

npm install nrm -g
Copy the code

Switch to the specified server

nrm use taobao
Copy the code

Initialize the directory

npm init
Copy the code

The directory structure of the file now looks like this

Here are some of the file types in the directory

package.jsonFile:

The package.json file is used to describe information about a package!

As long as there is a qualified pacakge.json file in a folder, that folder can be called a package!

Qualified definition: Must contain two attributes name Version

Version Number Description

A version number usually contains three digits, with a middle number. Separate format: Major version number. Second version Number. Revised version number

Major version number: When the code function is updated, after the update, it is not compatible with the previous version, then need to update the major version number! This version number: when the code update function, after the update, still compatible with the previous version, just added some functionality, so you need to update the version number Revised version number: when the code updates, update just fix some bugs, or optimize the function of some, so this time only need to update the revised version is ok

Jquery: 1.x 2.x 3.x 1.10.1 1.12.4 1.12.1 1.12.4

Description of Dependencies and devDependencies

Both properties hold all the dependency information for the current package.

DevDependencies are required only at the time of development and not at the time of upload.

Question: Why should dependency information be stored? The main purpose is for code sharing when more convenient!

When sharing code, you don’t need to share node_modules. You just need to share your own code and pacakge.json. Other programmers can download all dependencies according to pacakge.json after they get the code.

NPM install This command automatically downloads packages based on the package information saved in package.json (devDependencies+dependencies)

Only the runtime dependencies can be downloaded using the command NPM install –production

How do I save information about dependencies into Dependencies and devDependencies

In earlier versions of NPM, dependency information was not saved automatically!

  1. Save the dependency information to DependenciesNPM install package - save NPM install package - S
  2. Save the dependency information to devDependenciesNPM install package - save - dev NPM install package - D

A package.json file will be generated after the initialization. This file will record some information about the folder, such as the entry file, the project name, which dependencies are installed, etc. Note that the project name cannot be webpack

4. Write index.html,main.js files

index.html

   <ul>
        <li>The test for</li>
        <li>The test for</li>
        <li>The test for</li>
        <li>The test for</li>
        <li>The test for</li>
        <li>The test for</li>
        <li>The test for</li>
        <li>The test for</li>

    </ul>
Copy the code

main.js

	// Import jQuery package
    import $ from 'jquery'// The library classes need to be installed
    // Set the background color of even lines, starting with 0, where 0 is even
    $('li:even').css('backgroundColor'.'lightblue');
    // Set the background color of odd lines
    $('li:odd').css('backgroundColor'.'pink');
Copy the code

Install the jquery class library

cnpm i jquery --save
Copy the code

At this time we according to the conventional method in the index. The HTML page. The introduction of the main js files, will be an error, because the main. The import $from js file ‘jquery’ is an advanced syntax that is not recognized by the browser, so use a packaging tool to process the main.js file, compile it into another file, and then import the compiled file into the page

Install the packing tool

npm i webpack  webpack-cli  -g

npm i webpack webpack-cli  -D
Copy the code

7. Create webpack.config.js

Create a new configuration file, webpack.config.js, that is the same as package.json, and set the packaging mode

module.exports={
    mode:"development"
}
Copy the code

Run, package code

webpack src/main.js dist/bundle.js
Copy the code

In this case, it’s dist/main.js instead of dist/bundle.js. So we introduce dist/main.js in the page, and that’s where we see main.js in action

Note that at this point, every time you modify the JS file, you need to re-execute the above packaging code to take effect, which is very troublesome. To solve this problem, we can use real-time packaging, see the method below

Use webpack configuration files to simplify packaging commands

  1. Since webpack needs to specify the path of the entry file and output file when running the webpack command, we need to specify the path of the entry file and output filewebpack.config.jsTo configure the two paths:
    // Import the module that handles the path
    var path = require('path');

    // Export a configuration object. When webpack is started, it will look for webpack.config.js by default and read the exported configuration object in this file for packaging
    module.exports = {
        entry: path.resolve(__dirname, 'src/js/main.js'), // Project entry file
       
        output: { // Configure the output options
            path: path.resolve(__dirname, 'dist'), // Configure the output path
            filename: 'bundle.js' // Configure the output file name
        },
        mode: 'development'
    }
Copy the code

Note:

  • In the previous example, the project entry file main.js was not in the js directory, so we had to manually move the entry file main.js to the js directory
  • After this step, every time you modify the main.js file, just executewebpackCommand to repackage
  • However, in the page you will notice that the modified main.js file does not seem to have any effect, that is because we are inwebpack.config.jsThe export file is specified as:dist/bundle.js“, so we’re going to package and compile the files we introduced earlier in index.htmldist/main.jsInstead ofdist/bundle.jsYou can see the effect

Here’s a bonus point:

Resolve () and path.join() in node’s path module

Introduction of path module. Direct reference. A built-in module in Nodeconst path = require('path'); Path. join(path1, path2, path3.......) What it does: Uses a specific delimiter for a path fragment (window: \) join to form a path and normalize the generated path. If any path segment type is incorrect, an error message is displayed.const path = require('path');
let myPath = path.join(__dirname,'/img/so');
let myPath2 = path.join(__dirname,'./img/so');
let myPath3=path.join('/foo'.'bar'.'baz/asdf'.'quux'.'.. ');
 
 
console.log(__dirname);//__dirname, the file path
console.log(myPath);    
console.log(myPath2);   
console.log(myPath3); Third, the path. Resolve ([from. ] To resolves a sequence of paths or path fragments into an absolute path. This is equivalent to executing the CD operation. / is resolved to root.let myPath = path.resolve(__dirname,'/img/so');
let myPath2 = path.resolve(__dirname,'./img/so');
let myPath3=path.resolve('/foo/bar'.'./baz');
let myPath4=path.resolve('/foo/bar'.'/tmp/file/');
 
console.log(__dirname);           
console.log(myPath);    
console.log(myPath2);   
console.log(myPath3);  
console.log(myPath4);
Copy the code

Even though we have simplified the packaging tool, every time we change main.js, we still need to re-enter the command webpack for packaging. To solve this problem, we will install a plug-in for real-time packaging, after each change, automatic packaging, how nice

Ix. Realize real-time packaging construction of Webpack

  1. Run CNPM I webpack-dev-server –save-dev to install to the development dependency

  2. Error :’webpack-dev-server’ is not an internal or external command, nor is it a runnable program or batch file.

  3. In this case, use the package.json command to run the webpack-dev-server command and add the “dev”: “webpack-dev-server” command under the scripts node

  4. NPM run dev finds that bundle.js can be packaged in real time, but no bundle.js file is generated in dist directory. This is because webpack-dev-server stores the packaged file in memory. Because it needs to be packaged and compiled in real time, it can be very fast in memory

  1. At this time, visit the http://localhost:8080/ website launched by webpack-dev-server and find a folder panel. You need to click to the SRC directory to open our index home page.

  2. because the bundle.js file is in memory

  3. NPM run dev: NPM run dev: http://localhost:8080/ “Webpack-dev-server –contentBase SRC –open”, specifying the root directory to boot from

Ten.html-webpack-pluginPlug-in configuration startup page

Why install this plugin: Remove requests for JS files from the Index page

The use of the –contentBase command is cumbersome, and you need to specify the directory to start from and modify the SRC attribute of the script tag in index.html. Therefore, it is recommended to use the html-webpack-plugin to configure the start page.

  1. runcnpm i html-webpack-plugin --save-devInstall to development dependencies
  2. Modify thewebpack.config.jsThe configuration file is as follows:
   // Import the module that handles the path
    var path = require('path');
    // Import a plug-in that automatically generates HTMl files
    var htmlWebpackPlugin = require('html-webpack-plugin');

    module.exports = {
        entry: path.resolve(__dirname, 'src/js/main.js'), // Project entry file
        output: { // Configure the output options
            path: path.resolve(__dirname, 'dist'), // Configure the output path
            filename: 'bundle.js' // Configure the output file name
        },
        plugins: [// Add the plugins node configuration plug-in
            new htmlWebpackPlugin({
                template:path.resolve(__dirname, 'src/index.html'),// Template path
                filename:'index.html'// The name of the automatically generated HTML file}})]Copy the code
  1. Modify thepackage.jsonIn thescriptThe dev command in the node is as follows:
"dev": "webpack-dev-server --open"
Copy the code
  1. Comment out compiled files with script tags introduced in index.html becausehtml-webpack-pluginThe plugin will automatically inject bundle.js into the index.html page!

NPM run dev automatically opens index.html. Each time you modify the entry file, it changes back to automatic packaging and the page automatically refreshes

Implement automatic browser opening, hot update and configure the default browser port number

Note: Hot updates are not obvious in JS, which can be explained by CSS in a moment!

A:

  • Modify thepackage.jsonThe script node of--openAutomatically open the browser.--port 4321Indicates that the open port number is 4321.--hotTo enable hot update of the browser:
"dev": "webpack-dev-server --hot --port 4321 --open"
Copy the code

Method 2:

  1. Modify thewebpack.config.jsFile, addeddevServerNodes are as follows:
devServer:{
        hot:true,
        open:true,
        port:4321
    }
Copy the code
  1. Introduce in the headwebpackModule:
var webpack = require('webpack');
Copy the code
  1. inpluginsAdded the following information under the node:
new webpack.HotModuleReplacementPlugin()
Copy the code

Package CSS files with Webpack

  1. runcnpm i style-loader css-loader --save-dev
  2. Modify thewebpack.config.jsThis configuration file:
Module: {// Configure the rules of the third-party loader module: [// file matching rules {test: /\.css$/, use: ['style-loader', 'css-loader']}// Rules for handling CSS files]}Copy the code
  1. Note:useIndicates which modules to use for processingtestMatched files;useThe call sequence of relevant Loader modules is called from back to front.
  2. Import the CSS file into the entry file (js file) with the actual path as the main
import "./css/index.css"
Copy the code

Use Webpack to pack less files

index.less

ul{
  padding: 0;
  margin: 0;
}
Copy the code
  1. runcnpm i less-loader less -D
  2. Modify thewebpack.config.jsThis configuration file:
{ test: /\.less$/, use: ['style-loader', 'css-loader', 'less-loader'] },
Copy the code

Package sass files with Webpack

HTML, body{margin: 0; padding: 0; li{ font-size: 12px; line-height: 30px; }}Copy the code
  1. runcnpm i sass-loader node-sass --save-dev
  2. inwebpack.config.jsAdd the loader module to process sass files:
{ test: /\.scss$/, use: ['style-loader', 'css-loader', 'sass-loader'] }
Copy the code

Use Webpack to handle paths in CSS

  1. runcnpm i url-loader file-loader --save-dev
  2. inwebpack.config.jsAdd loader module to handle URL path:
{ test: /\.(png|jpg|gif)$/, use: 'url-loader' }
Copy the code
  1. Can be achieved bylimitSpecify the base64 encoded image size; Only images smaller than the specified byte are base64 encoded:
{ test: /\.(png|jpg|gif)$/, use: 'url-loader? limit=43960' },Copy the code

Use Babel to handle advanced JS syntax

  1. runcnpm i babel-core babel-loader babel-plugin-transform-runtime --save-devInstall the relevant loader packages for Babel
  2. runcnpm i babel-preset-es2015 babel-preset-stage-0 --save-devInstall the syntax for the Babel transformation
  3. inwebpack.config.jsTo add the relevant loader module, which needs to be noted that must be putnode_modulesAdd folders to exclusions:
{ test: /\.js$/, use: 'babel-loader', exclude: /node_modules/ }
Copy the code
  1. Add in the project root directory.babelrcFile and modify this configuration file as follows:
{
    "presets":["es2015", "stage-0"],
    "plugins":["transform-runtime"]
}
Copy the code
  1. Pay attention to: syntax pluginbabel-preset-es2015Can be updated tobabel-preset-env, which contains all ES related syntax;

After:

Above is webpack packaging tool application case, the case can also be packaged as a project template, we are studying in this piece of content, to master some basic knowledge, otherwise, encountered an error problem, may be impossible to solve webpack other esoteric knowledge, suggest you to look at the official documentation