The ultimate goal

You can use Webpack to package vUE projects.

The overall plan

  1. Webpack installation and easy to use
  2. Add packaging functionality through configuration files
  3. Learning about various loaders allows Webpack to package various files
  4. Learn the power of Plugins’ powerful WebPack
  5. Learning to configure Webpack-dev-Server can update preview code in real time during development
  6. Configure webPack to implement.vue file packaging

Webpack – Install basic use

Learning goals

  • Understand what Webpack does.
  • Master the basics of Webpack.
  • Resolve code packaging issues in projects. (Package the code with WebPack)

A study plan

  1. The usefulness of Webpack.
  2. Installation environment for WebPack
  3. The installation of the webpack
  4. Code file structure
  5. How do I make a normal code file modular for Easy WebPack
  6. Preview the Webpack effect with a simple command
  7. View the packed JS and briefly introduce the webpack packaging basis.
  8. Package using WebPack via ES6 modular files
  9. conclusion

Begin to learn

The world of Webpack is all modules

1. Webpack’s role (packaging)

Webpack collects, combs and packs modules

  • Package the projects we develop (compile, convert our code into code that the browser can compile, e.g. Es6 to ES5, SCSS to CSS, add prefixes to CSS, split.vue into.js and.css)
    • Compile constantly during development
      • Generate a temporary local service from WebPack Server to compile the code for the project we are developing.
    • Package the resources after the project is developed
      • The compression
      • Without compression

2. Install webpack

Webpack Chinese website

1. Installation environment

  1. Install Node. Currently, installing Node automatically installs NPM.

    The node Chinese website

  2. Create a folder. For example, not

  3. Use the NPM command to initialize the Node environment.

    npm init -y
    Copy the code

    This produces a package.json file

    {
      "name": "demo1"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": []."author": ""."license": "ISC"
    }
    
    Copy the code

2. Install webpack

1. Enter a value in the CLI tool (partial installation is recommended).

npm i webpack webpack-cli -D
Copy the code

If the following code is displayed on the command line, the installation is successful.

+ webpack-cli@3.3.12
+ webpack@4.43.0
added 391 packages from 218 contributors in 56.033s
Copy the code
"DevDependencies" : {" webpack ":" ^ 4.43.0 ", "webpack - cli" : "^ 3.3.12"}Copy the code

I is short for install

-d is short for –save-dev, which stores the package name and version in devDependencies of package.json, and –save stores the package name and version in devDependencies.

“DevDependencies” refers to dependencies at runtime. “devDependencies” refers to dependencies at development time.

Webpack 4x, webpack will command related content in webpack-CLI, so you need to install Webpack-CLI.

Note:

  1. It is recommended to install webpack and webpack-CLI at the same time to ensure that webpack-CLI corresponds to the currently installed Webpack.

  2. Not calling the project Webpack will cause the installation to fail.

  3. How do I view the version number? Webpack cannot be used because it is not a globally installed view version

    webpack -v
    Copy the code

    It USES

    node_modules\.bin\webpack -v
    / / 4.43.0
    Copy the code

    or

    npx webpack -v
    // 4.43.0
    Copy the code

Note that the NPM version number is required after 5.2.

NPX webpack equivalent to node_modules\.bin\webpack

3. Create the basic file code

Once the environment is ready we start creating a few basic files with the following directory structure:

deomo1/root
|-index.html
|-index.js
|-package.json
|-tool.js
Copy the code

Index.html code


      
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<body>
    <div id="app"></div>
</body>
<script src="tool.js"></script>
<script src="./index.js"></script>
</html>
Copy the code

Tool. Js code

const updateDom = (id, content) = >{
    window.document.getElementById(id).innerHTML =  content
}
Copy the code

The index. The js code

updateDom('app'.'Pass the Wisdom Podcast')
Copy the code
Pain points
  1. Index.js depends on tool.js so files in index.html cannot be repositioned

  2. There is no guarantee that variables are unique (variable conflicts) when developing a multi-player project. For example, the two files have tool.js var a = 100. Js var a =1000;

  3. Older browsers do not recognize ES6 syntax.

  4. The code is not obfuscated and there are security risks, such as someone can infer from your code some parameters of the server interface request.

  5. As the number of JS files increases, it increases the difficulty of project management, such as various JS file dependencies, variables and so on

The solution

Package multiple JS files into one by using webpBack.

4. Modify the basic file code to modular writing method

This code example is CommonJS modular writing method, the specific transformation is as follows

tool.js

const updateDom = (id, content) = >{
    window.document.getElementById(id).innerHTML =  content
}
// module in nodejs
module.exports = {
    updateDom
}
Copy the code

index.js

const {updateDom} = require('./tool');
updateDom('app'.'Pass the Wisdom Podcast')
Copy the code

After the code was changed, we opened it directly through the browser again and found that the browser reported an error because the browser could not recognize it. Next we pack our Diamond via Webpack.

Pay attention to

In WebPack 4, it can be used without any configuration.

  1. Simple packaging operation

    npx webpack index.js // Import file
    Copy the code

    NPX is explained above

    The results of

    Hash: c4b4044439973defe187
    Version: webpack 4.43.0
    Time: 425ms
    Built at: the 2020-07-16 4:51:35PM
      Asset      Size  Chunks             Chunk Names
    main.js  1.05 KiB       0  [emitted]  main
    Entrypoint main = main.js
    [0] ./index.js 71 bytes {0} [built]
    [1] ./tool.js 160 bytes {0} [built]
    Copy the code

    At the same time, the root directory generates a folder called dist that contains a main.js file.

    There is also a yellow warning, because we didn’t tell WebPack whether the mode we need to package is development mode (which I understand as development code) or production mode (which I generally understand as package and go live).

5 Packaged JS

Main.js is the result of the index.js and tool.js files.

The basics WebPack analyzes the reference relationships in the entry file and merges related files together, for example:

If tool.js is not referenced in index.js then packaged main.js has no code for tool.js.

(Show the students the mian.js.)

6. Introduce packaged JS

Modified index. HTML


      
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<body>
    <div id="app"></div>
</body>
    <script src="./dist/main.js"></script>
</html>

Copy the code

7. Use the modular export of ES6

Create a tooles6.js file

const log = (content) = > {
    console.log(Date.now(), content)
}

// Es6 modular export
export { log }

Copy the code

In the index.js file

// Node module import
const {updateDom} = require('./tool');

 // Es6 module import
import {log} from './tooles6';

updateDom('app'.'Pass the Wisdom Podcast')

log('Test webpack to see if it recognizes es6 modularity')

Copy the code

summary

  1. Webpack automatically identifies various dependency processing packages
  2. Webpack through the entry file
  3. Webpack can be used to package multiple or one JS file.
    1. Pros: Don’t worry about their dependencies
  4. You are not advised to install node.js globally-DInstall to the project.
  5. Each package will generate a new file, if the same name will be overwritten
  6. Two types of modularity are supported
    1. commonjs
    2. es6

Webpack – Basic configuration

Learning goals

How do we configure WebPack to meet our needs?

How can we simplify webpack commands so they can be used quickly

How do we customize the packaging entry and exit paths?

Through the following courses we can master the basic configuration of Webpack to meet the basic needs of our project packaging.

A study plan

  1. Create the default configuration file webpack.config.js
  2. Specify the configuration file to package
  3. Use package.json to simplify webpack commands
  4. Custom package file and output file location and name
  5. conclusion

Begin to learn

In WebPack 4, it can be used without any configuration, however most projects will require complex setup, which is why WebPack still supports configuration files. This is much more efficient than manually typing a lot of commands into a terminal, so let’s create a configuration file instead of using cli commands.

A quote from the official website

When WebPack is at work, it defaults to looking for a file called webpback.config.js in the root directory (if it can’t find it, it uses some default Settings).

Webpback.config. js is the configuration file of Webpack. In this configuration file, we can configure the parameters of Webpback by exporting a JSON object one by one, making packaging more flexible.

1. Create the default configuration file webpack.config.js

location

Let’s first specify the packaging mode mode

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

Next, run the package command again to view the contents of the resulting main.js file and compare the changes between.

  1. The yellow warning is gone because we have set mode.
  2. We can think of the WebPack configuration file as webpack being a function that takes an object and uses it to make the Webapck function produce the result we want.

The point of this file is to export a configuration item that configures how webPack is packaged.

At the operational level, it’s about learning how to use the file.

Mode mode:

  • Development: Development mode (code does not compress confusion)
  • Production: Production mode (compression, obfuscation, encryption……. Do not read)

2. Specify the configuration file (custom configuration file name)

purpose

To implement multiple packaging modes, such as development mode and production mode, we can write it in a configuration file but it is not maintainable.

I recommend writing separate configuration files for different functions, and this is often the case at work.

By default, Webpack looks for a file named webpack.config.js as its configuration file, but it is up to us to decide which configuration file to use for different scenarios. In other words, the configuration file does not have to be called webpack.config.js.

Next, create a webpack.dev.js file and use it as a configuration file, and use it for packaging

1. Create a custom configuration file in the root directory

Create webpack.dev.js in the project root directory as follows:

module.exports = {
  mode: 'development'.output: {filename:'bundle.js'}}Copy the code

2. Use this file to package the configuration

The basic format
NPX webpack --config Webpack configuration file entry fileCopy the code
Run the command
npx webpack --config webpack.dev.js index.js
Copy the code

3. Simplify running commands with scripts in package.json

The basic format
"scripts": {
    "Custom command name": "Code to execute",}Copy the code
The sample
"scripts": {   
    "build": "webpack --config webpack.dev.js index.js"
 }
Copy the code
Run the command
NPM run build // equivalent to NPX webpack --config webpack.dev.js index.jsCopy the code

4. Set the package import file and export path

In webpack:

  • The default entry is./ SRC /index.js
  • The default exit is./dist/main.js.

1. Set an entrance path

In practice, the entry file is usually not index.js or app.js

Adjusting the directory structure

|-package.json
|-index.html
|-src/
|-src/js
|-------app.js
|-------tool.js
|-------tooles6.js
Copy the code
  • Change the name of SRC /index.js to SRC /js/app.js

  • Add entry to the webpack.config.js configuration item as follows

  • module.exports = {
      mode: 'development'.// Packing method
      entry:'./src/js/app.js' // Import file
    }
    Copy the code
  • Example Modify the quick pack command

    • "scripts": {
         "build": "webpack"
       }
      Copy the code
    • Since we are using webpack.config.js, there is no need to use –config webpack.config.js to specify the configuration file.

  • Repackage tests

npm run build
Copy the code

2. Set an egress path

  • Add output to the webpack.config.js configuration item as follows

    • // Introduce the core module in nodeJS
      const path = require('path') 
      console.log(path.join(__dirname,'/build'))
      module.exports = {
          mode: "production".entry: './src/js/app.js'.// Import file
          output: {
              "path": path.join(__dirname,'/build'), // Decide where the export documents are
              "filename": "bundle.js" // Set the name of the export file. By default, it is called main.js}}Copy the code
    • Description:

      • Filename in output is used to specify the name of the packaged file.
      • The path in output is used to specify the packaged path. Note: It must be an absolute path. So, the resolve method in the Path module is referenced to generate the absolute path.
      • If the path does not exist, it automatically creates a default path namedist.
  • Repackage tests

npm run build
Copy the code

summary

  • The default configuration file name for Webpack is webpack.config.js
  • Webpack configuration files can also be individually specified to meet the needs of multiple scenarios.
  • Learn webpack and learn how to use webpack.config.js.
  • Integrating webpack’s packaging command into Script simplifies the packaging command and makes it easier for other collaborators to use.
  • Define your own import and export files

Soul three q

What’s the use?

packaging

Why use it?

Engineering: Front-end tasks need to be managed by tools

Development and launch

How does it work?

Don’t memorize webpack.config.js, read the documentation, just remember the most basic configuration function.

Webpack – Advanced configuration

1. loader

introduce

Why loader?

Webpack can only process.js files without loader, but there are files of various formats in our project, and js files need to be further processed, such as ES6 to ES5.

Purpose 1.

Use loader to convert the syntax of the file to be packaged.

2. The role

Read each file in the form of a string, parse and convert it.

Principle 3.

Loader can be interpreted as a translator, converting source files to output results, and a file can be translated multiple times.

Loader is also a module, exported by default as a node function that is called when the Loader is converting resources and accessed through this context.

module.exports = function(source) {
  // source is the original content of a file passed to the Loader by the Compiler
  // This function needs to return the processed content. For simplicity, this function returns the original content, equivalent to the 'Loader' did not do any conversion
  return source;
};
Copy the code

Conversion: A Loader has a single responsibility and only needs to complete one conversion. If a source file needs to go through a multi-step conversion to work properly, use multiple Loaders to convert it. When multiple Loaders are called to convert a file, each Loader will execute in chain order. The first Loader will get the original content to be processed, the result of the previous Loader will be passed to the next one for subsequent processing, and the last Loader will return the final result after processing to Webpack. So, when you develop a Loader, keep its responsibilities simple and you only care about the inputs and outputs.

The instance

1. Use CSS-loader to process the. CSS file in the style-loader file

To prepare

public.css

body.html{
    padding:0;
    font-size:14px;
}
Copy the code

style.css

@import "public.css";
div {
  border:4px solid #ccc;
  width: 50%;
  height: 200px;
  margin:30px auto;
  box-shadow: 3px 3px 3px #ccc;
  background-color: #fff;
  text-align: center; 
}
Copy the code

App.js added to introduce CSS files

// Node module import
const {updateDom} = require('./tool');
 // Es6 module import
import {log} from './tooles6';
// add new CSS file import
import '. /.. /css/style';

updateDom('app'.'Pass the Wisdom Podcast')

log('Test webpack to see if it recognizes es6 modularity')
Copy the code

Use WebPack packaging

npm run bulid
Copy the code

Console at this point

We can see the console error, here we only need to pay attention to the key sub-loader and file format. CSS, from which we can infer that csS-Loader is missing

CSS – loader installation

npm install css-loader -D
Copy the code

-d devDependencies is a dependency at development time

css-loaderConfigure in WebPack

module.exports = {
    module: {
        rules: [{test: /\.css$/.use: ['css-loader']},],}}Copy the code

Add Module objects inside the expors object and configure rules array for loader configuration

Order of execution: Execute from the end of the array, or simply from right to left.

Execute commands and results

CSS loader is used to help Webpack read the.css file and package it into bundle.js. Style-loader is also required

The installation

npm i style-loader -D
Copy the code

use

module.exports = {
    module: {
        rules: [{test: /\.css$/.use: ['style-loader'.'css-loader']},],}}Copy the code

Complete code:

const path = require('path') 
console.log(path.join(__dirname,'/build'))
module.exports = {
    mode: "production".entry: './src/js/app.js'.// Import file
    output: {
        "path": path.join(__dirname,'/build'), // Decide where the export documents are
        "filename": "bundle.js" // Set the name of the export file. By default, it is called main.js
    },
    module: {
        rules: [{test: /\.css$/.use: ['style-loader'.'css-loader']},],}}Copy the code

Let’s take a look at the output.js package

Bundle.js has some JS code that, at runtime, automatically appends the style tag to the.html file and outputs the style.

extension

eval("var api = __webpack_require__(/*! . /.. /node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js */ \"./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js")
Copy the code

To node_modules \ style – loader \ dist \ runtime \ injectStylesIntoStyleTag js find insertStyleElement under this approach, you can find the process.

function insertStyleElement(options) {
  var style = document.createElement('style');
  var attributes = options.attributes || {};

  if (typeof attributes.nonce === 'undefined') {
    var nonce = typeof__webpack_nonce__ ! = ='undefined' ? __webpack_nonce__ : null;

    if(nonce) { attributes.nonce = nonce; }}Object.keys(attributes).forEach(function (key) {
    style.setAttribute(key, attributes[key]);
  });

  if (typeof options.insert === 'function') {
    options.insert(style);
  } else {
    var target = getTarget(options.insert || 'head');

    if(! target) {throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");
    }

    target.appendChild(style);
  }

  return style;
}
Copy the code

The browser is ready to render the style.

Note the configuration sequence of the Loader.


Section CSS-loader helps Webpack pack.css into the style-loader. The style-loader converts the packed.css into the HTML as a style tag.

** @import is used to import another CSS file.

grammar

@import url;
@import url list-of-media-queries;
@import[ <string> | <url> ] [ <media-query-list> ]? ;Copy the code

explain

  • Url: Is said to the introduction of resource location] (https://developer.mozilla.org/zh-CN/docs/Web/CSS/string) or [. This URL can be absolute or relative path. Note that this URL doesn’t need to specify a file; you can just specify the package name.
  • list-of-media-queriesIt’s comma separatedMedia queriesA list of conditions that determine under which CSS rules introduced through urls are applied. If the browser does not support any of the media query criteria in the list, the CSS file specified by the URL will not be imported.

The instance

  • Used in the CSS file
/* Method 1 */
@import 'test.css';
/* Method 2 */
@import url(test.css);
/* @import url list-of-media-queries; * /
@import "common.css" screen, projection;
@import url('landscape.css') screen and (orientation:landscape);
Copy the code
  • Js file
 import 'test.css';
Copy the code
2. Use less-loader to process. Less files

The installation

npm i less-loader  -D
// Do not install less
npm i less-loader less  -D
Copy the code

Less-loader: loads less files and converts.less syntax code to.css

configuration

module.exports = {
    module: {
        rules: [{test:/\.less$/.use: ['style-loader'.'css-loader'.'less-loader'}],}}Copy the code

The complete code

const path = require('path') 
console.log(path.join(__dirname,'/build'))
module.exports = {
    mode: "development".// development production
    entry: './src/js/app.js'.// Import file
    output: {
        "path": path.join(__dirname,'/build'), // Decide where the export documents are
        "filename": "bundle.js" // Set the name of the export file. By default, it is called main.js
    },
    module: {
        rules: [{test: /\.css$/.use: ['style-loader'.'css-loader'] {},test:/\.less$/.use: ['style-loader'.'css-loader'.'less-loader'}],}}Copy the code

Pay attention to the loader sequence of less files

 use:['style-loader'.'css-loader'.'less-loader']
Copy the code

Principle: Less and convert it to CSS. Send the converted result to CSS-loader. The CSS-loader processes the result to the style-loader. If the less-loader is configured, the Webpback cannot recognize the CSS format. Since each test is a processing module, Webpack does not apply the test:/.css/ rule to /.less/

Code transformation

index.less

@import "style.css"; body{ div { border:4px solid #ccc; width: 50%; height: 200px; margin:30px auto; box-shadow: 3px 3px 3px #ccc; background-color: #fff; text-align: center; }}Copy the code

app.js

// Node module import
const {updateDom} = require('./tool');
// Import less files
import '.. /css/index.less'
// Import the CSS file
// import './.. /css/style.css';
 // Es6 module import
import {log} from './tooles6';

updateDom('app'.'Pass the Wisdom Podcast')

log('Test webpack to see if it recognizes es6 modularity')
Copy the code

Execute the package command and view it in your browser

3. Run the url-loader file-loader command to process image resources

Front-end development inevitably uses a variety of image resources

Code transformation

But less file

 @import "style.css";

body{ 
  div {
    border:4px solid #ccc;
    width: 50%;
    height: 200px;
    margin:30px auto;
    box-shadow: 3px 3px 3px #ccc;
    background-color: #fff;
    text-align: center; 
    background-image: url(./../img/webpack-png.png);
  }
}
Copy the code

Install the url – loader

npm i url-loader - D
Copy the code

configuration

module.exports = {
    module: {
        rules: [{test:/\.png/.use: ['url-loader'}],}}Copy the code

perform

npm run build
Copy the code

The results of

We found only one JS file because url-loader converted the image file to Base 64.

Advantages: Reduced network requests.

Disadvantages: Increased JS package size.

Base64 is generally slightly larger than the image.

How to choose?

Small files can be converted to Base 64. Large files are not recommended.

Url-loader Advanced configuration

Use :[‘xxx-loader’]

General rules

use:[
    {
        loader:'xxx-loader'.options: {}}]Copy the code

If you are not familiar with NPM, you can find the corresponding loader, for example

The code after configuration

const path = require('path') 
console.log(path.join(__dirname,'/build'))
module.exports = {
    mode: "development".// development production
    entry: './src/js/app.js'.// Import file
    output: {
        "path": path.join(__dirname,'/build'), // Decide where the export documents are
        "filename": "bundle.js" // Set the name of the export file. By default, it is called main.js
    },
    module: {
        rules: [{test: /\.css$/.use: ['style-loader'.'css-loader'] {},test:/\.less$/.use: ['style-loader'.'css-loader'.'less-loader'] {},test:/\.png/.use: [{loader:'url-loader'.options: {limit:3*1024 // 3* 1024b = 3kb}}]}],}}Copy the code

The build result is as follows:

This is because we configure url-loder so that it only processes images below 3k and switch to base64. If we need to process images larger than 3KB, we need to use file-loader.

The installation file – loader

npm i file-loader -D
Copy the code

Result of executing code

At this point, we find that file-loader is not configured and can be used directly.

Pay attention to

Browser view

No image is displayed on the page because file-loader simply copies the image over. When we look at the path, we can’t find it in the browser. Right click to view the image path, we can clearly see that our image path location is wrong

why

The above code sets the limit option, which means that when the image size is less than 8192 bytes, the base encoding string is converted, and when the image size is greater than 8192 bytes, the default file loader is used.

Solution (if you are looking at the notes to learn, here is a suggestion to understand directly skip, because later through webpack new plugin configuration will solve this problem, don’t waste time here)

Change the CSS reference path to the path after file-loader processes the image.

  1. The mini-CSS-extract-plugin tool is configured as follows

But the Mini-CSS-extract-plugin is usually used for project packaging.

The extension configuration

Our urL-loader is powerful and can handle files in various formats. How to optimize the configuration? Specific as follows

{
    test:/(\.png|\.jpg|\.svg)/,
    use:[{
        loader:'url-loader',
        options:{
        limit:3*1024 // 3* 1024b = 3kb
        }
    }]
}
Copy the code

We use regular expressions to write the files we want to use url-loader to test so that we can match.

Optimized configuration You can modify the name and output location of a packaged image by setting name

{
    test:/\.png/.use: [{loader:'url-loader'.options: {limit:3*1024.// 3* 1024b = 3kb
                name:'img/[name].[ext]'}}}]Copy the code

Since our output path says build, the name can be the same as above. Name is the original file name and ext is the file type

Testing SVG files

Code transformation

index.less

@import "style.css"; body{ background: url(./.. /img/webpack-svg.svg); div { border:4px solid #ccc; width: 50%; height: 200px; margin:30px auto; box-shadow: 3px 3px 3px #ccc; background-color: #fff; text-align: center; background-image: url(./.. /img/webpack-png.png); }}Copy the code

Perform packaging

Since our SVG image is smaller than 3k, urL-loader converts SVG resources into Base64 and into JS

Loader summary

How to use

  1. Download the corresponding Loader based on the file type.
  2. Configure the loader.

2. The plugin plug-in

introduce

Purpose 1.

Plug-ins are designed to solve other things that loader cannot implement.

2. The role

Plugin is a function that extends Webpack,

3. Summary of commonly used Plugin

html-webpack-plugin

Function: copy our own. HTML file to the specified package export directory, and introduce the relevant resource code.

mini-css-extract-plugin

What it does: This plug-in helps us extract CSS code into a separate file (instead of embedding it in an HTML file style).

clean-webpack-plugin

Before generating the package file, clear the directory.

The instance

1. mini-css-extract-plugin

The installation process

  1. Download the plugin
npm i mini-css-extract-plugin -D
Copy the code
  1. In the configuration file

webpack.config.js

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
Copy the code
  1. Modify rules in module.exports of webpack.config.js

    module.exports = {
        module: {rules:[
                 {
                     / / replace style - loadr for {loader: MiniCssExtractPlugin loader} this configuration is our commonly used package online writing.
                    test:/\.less$/.use: [{loader: MiniCssExtractPlugin.loader},'css-loader'.'less-loader']},]}}Copy the code
  2. Add plugins to module.exports of webpack.config.js. All plug-ins need to be new here

     plugins:[
            new MiniCssExtractPlugin({
                // [name], [hash] is a placeholder
                // name: indicates the name of the import file
                // hash: a random string of values used to distinguish this packaging from other packaging processes. Because the source file changes, the hash is different each time you pack
                filename: '[name]-[hash].css',})]Copy the code

    The complete code

    const path = require('path') 
    +const MiniCssExtractPlugin = require('mini-css-extract-plugin');
    console.log(path.join(__dirname,'/build'))
    module.exports = {
        mode: "development".// development production
        entry: './src/js/app.js'.// Import file
        output: {
            "path": path.join(__dirname,'/build'), // Decide where the export documents are
            "filename": "bundle.js".// Set the name of the export file. By default, it is called main.js
        },
        module: {
            rules: [{test: /\.css$/.use: ['style-loader'.'css-loader'] {},test:/\.less$/,
       +             use:[{loader: MiniCssExtractPlugin.loader},'css-loader'.'less-loader'] {},test:/(\.png|\.jpg|\.svg)/.use: [{loader:'url-loader'.options: {limit:3*1024.// 3* 1024b = 3kb                       
                        }
                    }]
                }
            ],
        },
    +    plugins:[
            new MiniCssExtractPlugin({
                // [name], [hash] is a placeholder
                // name: indicates the name of the import file
                // hash: a random string of values used to distinguish this packaging from other packaging processes. Because the source file changes, the hash is different each time you pack
                filename: '[name]-[hash].css',}})]Copy the code

Execute pack command

Pay attention to

In this case our index. HTML path is incorrect

Our index. HTML does not have a reference, so you can’t see the style when you open the browser. I think you can manually change the reference address of the CSS file.

2. html-webpack-plugin
  1. The installation
npm i html-webpack-plugin -D
Copy the code
  1. In the configuration file.

webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin');
Copy the code
  1. New HtmlWebpackPlugin in webpack.config.js plugins and configure it
plugins: [
    new HtmlWebpackPlugin({ // Package the output HTML
        minify: { // Compress HTML files
            removeComments: true.// Remove comments from HTML
            collapseWhitespace: true.// Remove whitespace and newline characters
            minifyCSS: true// Compress inline CSS
        },
        filename: 'index.html'.template: path.resolve('./index.html') // Specify the location of the module})]Copy the code

Remove references from HTML

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial - scale = 1.0 "> < title > Document < / title > <! -- <link rel="stylesheet" href="./src/css/style.css"> --> </head> <body> <div id="app"></div> </body> <! - not by webpack package < script SRC = "tool. The js" > < / script > < script SRC = ". / index. Js "> < / script > -- > <! Package the generated file path with webpack --> <! -- <script src="./build/bundle.js"></script> --> </html>Copy the code

Result of executing code

There is an HTML in build.

Delete configuration items compressed by HtmlWebpackPlugin

plugins: [
    new HtmlWebpackPlugin({ // Package the output HTML
        filename: 'index.html'.template: path.resolve('./index.html') // Specify the location of the module})]Copy the code

The result of packing

We found that the background image of the url-loader processing path was also displayed.

These configuration items can also be found on the NPM package website, so you don’t need to remember them. Next we will add a plug-in to consolidate our knowledge.

3. clean-webpack-plugin

Download the plugin

npm i clean-webpack-plugin -D
Copy the code

Configuration file webpack.config.js

const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
    plugins: [
    new CleanWebpackPlugin()
]	
}

Copy the code

perform

All the code

const path = require('path') 
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
console.log(path.join(__dirname,'/build'))
module.exports = {
    mode: "development".// development production
    entry: './src/js/app.js'.// Import file
    output: {
        "path": path.join(__dirname,'/build'), // Decide where the export documents are
        "filename": "bundle.js".// Set the name of the export file. By default, it is called main.js
    },
    module: {
        rules: [{test: /\.css$/.use: ['style-loader'.'css-loader'] {},test:/\.less$/.use: [{loader: MiniCssExtractPlugin.loader},'css-loader'.'less-loader'] {},test:/(\.png|\.jpg|\.svg)/.use: [{loader:'url-loader'.options: {limit:3*1024.// 3* 1024b = 3kb                       }}]}],},plugins: [new MiniCssExtractPlugin({
            // [name], [hash] is a placeholder
            // name: indicates the name of the import file
            // hash: a random string of values used to distinguish this packaging from other packaging processes. Because the source file changes, the hash is different each time you pack
            filename: '[name]-[hash].css',}).new HtmlWebpackPlugin({ // Package the output HTML
            minify: { // Compress HTML files
                removeComments: true.// Remove comments from HTML
                collapseWhitespace: true.// Remove whitespace and newline characters
                minifyCSS: true// Compress inline CSS
            },
            filename: 'index.html'.template: path.resolve('./index.html') // Specify the location of the module
        }),
        new CleanWebpackPlugin()
    ]
}
Copy the code

Plugin uses summary

Plugin is used to enhance webPack capabilities

With the experience of using the above three plug-ins, we summarize the steps and attention points of installing plug-ins

  1. NPM package download plug-in.
  2. Introduce the plug-in in the configuration file.
  3. New the plugin in the plugin array.

Note:

  1. Some plug-ins are directly exported functions, while others are exported objects, for exampleconst { CleanWebpackPlugin } = require('clean-webpack-plugin')When we reference the NPM package error can go to the NPM package official website to check the use of demo.
  2. All plug-ins must be instantiated with new in the plugins array.
  3. The order in which plug-ins appear in plugins is not the order in which they are called, but the order in which they are called is related to the webPack execution.

3. webpack-dev-server

Purpose: To update our code in real time during development.

How to configure it?

  1. Download packages using NPM

    npm i webpack-dev-server  -D
    Copy the code
  2. Configure in the outermost layer of the configuration file

    Module. exports = {// configuates the webpack-dev-server option devServer: {host:'127.0.0.1', // Configure the boot IP address port: 8081, // configure the port open:true// Configure whether to automatically open the browser} // other Settings}Copy the code
  3. Modify package.json quick start configuration

     "scripts": {
        "build": "webpack",
    +    "dev":"webpack-dev-server"
      },
    Copy the code

    Execute the newly configured command

    npm run dev
    Copy the code

    At this point, our browser is open and the port number is 8081. If we don’t want our project port number to conflict with other projects, we can remove the port and webpback will automatically generate a port number based on the current system port usage.

summary

Webpack-dev-server solves the problem of code preview in real time during our development process, and gives us a convenient development generation. It not only has such functions, but also can configure cross functions through it.

3. Webpoack processes.vue files

introduce

Purpose 1.

Packaged.vue files can be handled through Webpack

configuration

The code for

Vue file/vuecomponents/App. Vue

<template>
  <div>Vue component {{title}}</div>
</template>

<script>
  export default {
    name: ' ',
    data() {
      return {
        title:'Webpack -vue- Vue single file component here'}}}</script>

Copy the code

/js/main.js

import Vue from "vue"
import App from '.. /vuecomponents/app.vue'
new Vue({
  render(h) {
    return h(App)
  },
}).$mount("#app")
Copy the code

We refer to vUE here, so download vUE in NPM

npm i vue -D
Copy the code

Analysis of the

  1. We added main.js so we need to modify the configuration file entry
  2. We want WebPack to recognize.vue so vue-loader is installed
  3. Vue-template-compiler is used to parse. Vue templates
  4. Need to handle. Vue internal style all need to have vue-style-loader

Install dependencies

npm i vue-loader  vue-template-compiler vue-style-loader -D
Copy the code

Modify configuration webpack.config.js

  1. Modify the entry

     entry: './src/js/main.js'.Copy the code
  2. Add loader to the. Vue file

  3. Add VueLoaderPlugin

VueLoaderPlugin is required for vueloaderLoader after 15.*.

Vue-style-loader is similar to previous file-loader and does not need to be configured separately.

{
    // If it is a. Vue file, use the following loader
    test: /\.vue$/.loader: 'vue-loader'
}

Copy the code
const VueLoaderPlugin = require('vue-loader/lib/plugin')

Copy the code

The above code is a configuration example provided on the official website

plugins:[
    new VueLoaderPlugin()
]

Copy the code

The complete code

const path = require('path') 
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
    mode: "development".// development production
    entry: './src/js/main.js'.// Import file
    
    output: {
        "path": path.join(__dirname,'/build'), // Decide where the export documents are
        "filename": "bundle.js".// Set the name of the export file. By default, it is called main.js
    },
    module: {
        rules: [{test: /\.css$/.use: ['style-loader'.'css-loader'] {},test:/\.less$/.use: [{loader: MiniCssExtractPlugin.loader},'css-loader'.'less-loader'] {},test:/(\.png|\.jpg|\.svg)/.use: [{loader:'url-loader'.options: {limit:3*1024.// 3* 1024b = 3kb    
                        name:'img/[name].[ext]'}}}, {// If it is a. Vue file, use the following loader
                test: /\.vue$/.loader: 'vue-loader'}],},plugins: [new MiniCssExtractPlugin({
            // [name], [hash] is a placeholder
            // name: indicates the name of the import file
            // hash: a random string of values used to distinguish this packaging from other packaging processes. Because the source file changes, the hash is different each time you pack
            filename: '[name]-[hash].css',}).new HtmlWebpackPlugin({ // Package the output HTML
            
            filename: 'index.html'.template: path.resolve('./index.html') // Specify the location of the module
        }),
        new CleanWebpackPlugin(),
        new VueLoaderPlugin()
    ],
    devServer: {
        host: '127.0.0.1'.// Set the boot IP address
        port: 8081.// Configure the port
        open: true  // Set whether to open the browser automatically}}Copy the code

Effect of Executing a command

summary

  1. We have analyzed that loader is needed for processing. Vue.
  2. Therefore, it can be concluded that the modularization of Webpack is not complicated. When we use it to package our projects, we can find the corresponding dependent packages on the NPM package website or webpack website according to the file types to be processed
  3. We need to understand the common usage of Webpack and be able to understand why there are errors in the packaging process and how to configure them with the information webPack provides.

conclusion

  1. Webpack is a packaging tool
  2. In the world of Webpack everything is modular.
  3. Loader helps WebPack translate different files so that WebPack can package them
  4. The Plugin improves webPack packaging
  5. Vue-cli is also based on webpack development and implementation