1. Webpack profile

1.1 What is Webpack?

Webpack is a front-end resource builder, a static Module bundler. In webpack’s view, the front-end has many resource files (JS /json/ CSS /img/less/…). Will be treated as modules. It will carry out static analysis according to module dependencies and generate corresponding static resources (bundles).

1.2 Five core concepts of Webpack

  • Entry: The Entry indicates which file webPack starts packing as the Entry point, analyzing and building the internal dependency diagram.

  • Output: The Output indicates where the Output of resource bundles packaged by Webpack goes and how to name them.

  • Loader: Loader enables Webpack to handle non-javascript files (WebPack itself only understands Javascript).

  • Plugins: Plugins can be used to perform a wider range of tasks, from packaging optimization and compression to redefining variables in the environment.

  • Mode: Mode instructs WebPack to use the configuration of the corresponding Mode.

    options describe The characteristics of
    development: willDefinePluginprocess.env.NODE_ENVIs set todevelopment, enablingNamedChunksPluginNamedModulesPlugin. A runtime environment that allows code to be debugged locally
    production: willDefinePluginprocess.env.NODE__ENVIs set toproduction. To enable theFlagDependencyUsagePlugin.FlagIncludedChunksPlugin ModuleConcatenationPlugin.NoEmitOnErrorsPlugin.OccurrenceOrderPlugin.SideEffectsFlagPluginTerserPlugin. A runtime environment in which code can be optimized to live

2. Webpack initial experience:

The directory structure is as follows:

Code:

// index: entry starting file for Webpack

import data from "./test.json";
import test from "./test.css";
function add(x,y){
    return x + y
}
console.log(add(1.2))
console.log("I am a json",data);
Copy the code
//test.json
{
  "key": "Test JSON file packaging"
}

Copy the code
// test.css
body{
    background-color: #42b983;
    height: 1000px;
    width: 100%;
}
Copy the code

Index.html at the root of the folder:

  • herescriptI’m introducing the packaged onesmain.jsfile
  • buildA new folder for the root directory
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="./src/test.css">
</head>
<body>

<script src="./build/main.js"></script>
</body>
</html>
Copy the code

Installation and packaging operations:

Installation:
  • Install globally first:npm i webpack webpack-cli -g
  • Installation in the project:npm i webpack webpack-cli -D

Packaging:

  • Development environment:
    • Command:webpack ./src/index.js -o ./build --mode=development(-oIt means thatoutputOutput)
    • Function:webpackAbility to compile and packagejsandjsonFile, and can bees6Convert the modular syntax of the browser to a syntax that the browser can recognize.
  • Production environment:
    • Command:webpack ./src/index.js -o ./build --mode=production
    • Function: in the development configuration function on a function, compression code
Question:

Error found in packing after importing CSS file:

Conclusion:
  1. webpackCan deal withjsandjsonFile, cannot be processedcss/imgAnd other resources
  2. Generate environmentandThe development environmentwillES6Modularity compiles to browser-awaremodule
  3. The production environmentthanThe development environmentMore than aCompression jscode

3. Webpack resources:

1. TocssandlessPackaging:

  • Create one at the root of your projectwebpack.config.jsFile, which is mainly used to tellwebpackYou're going to do something
  • const {resolve} = require("path");: used to concatenate absolute paths
    • resolve(__dirname,"build"): __dirnameRepresents theThe absolute directory path of the current file, it isnodejsA variable of
  • The module of the rulesIs used to configureloaderthe
    • testTo match files
    • useTo process matching files,useThe order of execution in the array isFrom the bottom up
  • packaginglessFile when you need to pay attention to installationlessandless-loader.lessDo not configure touseIn the array
// Tell webpack what to do

// All build tools run on the NodeJS platform and modularity defaults to commonJS syntax

const {resolve}   = require("path");

module.exports = {
    / / the entry
    entry:"./src/index.js"./ / export
    output: {// Package the output file name
        filename:"build.js".//__dirname represents the absolute directory path of the current file and is a variable of nodejs
        path:resolve(__dirname,"build")},/ / loader configuration
    module: {rules: [// Detailed loader configuration
            {
                //test -- matches a.css file ending
                test:/\.css$/.// Use means which loaders are used for processing. The order of execution in the use array is from bottom to top
                use:[
                    // Insert the style tag and js style resources into the head
                    "style-loader".//css-loader converts CSS files into commonJS modules and loads them into JS modules
                    "css-loader"] {},//test -- matches a.css file ending
                test:/\.less$/.// Use means which loaders are used for processing. The order of execution in the use array is from bottom to top
                use:[
                    // Insert the style tag and js style resources into the head
                    "style-loader".//css-loader converts CSS files into commonJS modules and loads them into JS modules
                    "css-loader"."less-loader",]}]},/ / the plugin
    plugins: [// Detailed configuration of the plug-in]./ / mode
    mode:"development"
}
Copy the code

For 2.htmlPackaging:

The HTML is processed here using a plug-in.

npm i html-webpack-plugin -D
Copy the code
webpack.config.jsCode:
  • The installation finishedhtml-webpack-pluginAfter that, use is neededThe introduction ofthe
    • const HtmlWebpackPlugin = require("html-webpack-plugin");
  • template: Just a template, copy"./src/index.html"File resources, and automatically import packaged output all resources (JS/CSS)
//webpack.config.js
const {resolve} = require("path");
const  HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports={
    entry:"./src/index.js".output: {filename:"html.js".path:resolve(__dirname,"build")},module: {rules: []},plugins: [// Create an empty HTML by default, automatically import packaged output all resources (js/ CSS)
            new HtmlWebpackPlugin({
                // Copy the "./ SRC /index.html" file resources and automatically import the package output all resources (js/ CSS)
                template:"./src/index.html"})].mode:"development"
}
Copy the code
Packing results:

You’ll notice that an extra index.html file is generated under the build folder

3. Packaging of image resources:

Folder structure:
├ ─ webpack. Config. Js ├ ─ SRC | ├ ─ BBB. Jpeg | ├ ─ index. The HTML | ├ ─ index. The js | └ index. The lessCopy the code
webpack.config.js:

There is no need to elaborate on the index.js and other contents of the entry, similar to the above. Let’s take a quick look at webpack.config.js configuration:

  • Used hereurl-loaderI’m going to do something with the image, buturl-loaderDepends on thefile-loader, so both need to be installed (only one is introduced)
  • optionsIn thelimit: Comments in the following code
const {resolve} = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin")
module.exports={
    entry:'./src/index.js'.output: {filename:"build.js".path:resolve(__dirname,"build")},module: {rules:[
            {
                test:/\.less$/,
                use:[
                    "style-loader"."css-loader"."less-loader",]}, {test:/\.(jpg|png|gif|jpeg)$/.// Use the single loader writing format
                // Download two packages, url-loader and file-loader, because url-loader relies on file-loader to work, so you need to download two packages
                loader:"url-loader".options: {// Effect: Images smaller than 8KB are base64 processed
                    // Advantages: Reduce the number of requests and reduce server stress
                    // Disadvantages: Larger image size (slower file request)
                    limit:8 * 1024}}},plugins: [new HtmlWebpackPlugin({
            template:"./src/index.html"})].mode:"development"
}
Copy the code
New problems:

Url-loader can process CSS images, but for HTML images, the packed build/index.html file is opened by the browser and the image cannot be displayed.

  • This is the timehtml-loader
  • url-loaderandhtml-loaderIn theoptionstheesModuleAll set tofalse
    • Reason: Shutdownurl-loaderthees6moduleModular, usingcommonjsThe modular
  • name:"[hash:10].[ext]":
  • [hash:10]:hashThe value of the former10position
  • [ext]: takes the original file name extension
const {resolve} = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin")
module.exports={
    entry:'./src/index.js'.output: {filename:"build.js".path:resolve(__dirname,"build")},module: {rules:[
            {
                test:/\.less$/,
                use:[
                    "style-loader"."css-loader"."less-loader",]}, {test:/\.(jpg|png|gif|jpeg)$/.// Use the single loader writing format
                // Download two packages, url-loader and file-loader, because url-loader relies on file-loader to work, so you need to download two packages
                loader:"url-loader".options: {// Effect: Images smaller than 8KB are base64 processed
                    // Advantages: Reduce the number of requests and reduce server stress
                    // Disadvantages: Larger image size (slower file request)
                    limit:8 * 1024.esModule:false.// Rename the image
                    name:"[hash:10].[ext]"}, {},test:/\.html$/.// html-loader is responsible for importing images from HTML that can be processed by urL-loader
                loader: "html-loader".options: {
                    esModule: false}}},plugins: [new HtmlWebpackPlugin({
            template:"./src/index.html"})].mode:"development"
}
Copy the code

4. Packaging of other resources:

Directory structure:
SRC ├─ └ iconfont.css ├─ └ Iconfont.eot ├─ └ Iconfont.svg ├─ └ Iconfont.ttF ├─ └ Iconfont.woff ├─index.html ├.jsCopy the code

The iconfont resource is used here for testing purposes

webpack.config.js
  • throughrulesObjects in theexclude:/\.(css|js|html)$/Excluding those suffixes leaves other files (font files, etc.)
  • throughfile-loaderTo handle the loading of other files
const {resolve} = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    entry:"./src/index.js".output: {filename:"build.js".path:resolve(__dirname,"build")},module: {rules:[
            {
                test:/\.css$/,
                use:[
                    "style-loader"."css-loader",]}, {// Use exclude to exclude these suffixes and all other resources are left
                exclude:/\.(css|js|html)$/,
                loader:"file-loader"}},plugins: [new HtmlWebpackPlugin({
            template:"./src/index.html"})].mode:"development"
}
Copy the code

4.webpack-dev-server

Modifying files in SRC requires manual compilation, and webpack-dev-server makes it possible to automate this

Go directly to webpack.config.js:

  • contentBase: Path after the project is built
  • compress: Enable or notgzipThe compression
  • port: the port number
  • open: Automatically opens after compiling
const {resolve} = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    entry:"./src/index.js".output: {filename:"build.js".path:resolve(__dirname,"build")},module: {rules:[
            {
                test:/\.css$/,
                use:[
                    "style-loader"."css-loader",]}, {// Use exclude to exclude these suffixes and all other resources are left
                exclude:/\.(css|js|html)$/,
                loader:"file-loader"}},plugins: [new HtmlWebpackPlugin({
            template:"./src/index.html"})].mode:"development".devServer: {// The path after the project is built
        contentBase:resolve(__dirname,"build"),
        // Start gzip compression
        compress:true./ / the port number
        port:3000.// Automatically open the browser after compiling
        open:true}}Copy the code