Front-end engineering

  • Modularization (JS modularization, CSS modularization, resource modularization)
  • (2) Componentization (reuse of existing UI structure, style, behavior)
  • ③ Standardization (division of directory structure, standardization of code, standardization of interface, standardization of documents, Git branch management)
  • ④ Automation (automated build, automated deployment, automated testing)

What is front-end engineering

  • concept
    • Based on modularization, componentization, standardization and automation, front-end project development is called front-end engineering
  • Why engineering
    • Engineering provides a set of standard development programs and processes, so that the front-end development system

Note: Vue and React projects in the enterprise are front-end engineering based on engineering development

Front-end engineering solutions

  • Early front-end engineering solutions:
    • Grunt (www.gruntjs.net/)
    • Gulp (www.gulpjs.com.cn/)
  • Current mainstream front-end engineering solutions:
    • Webpack (www.webpackjs.com/)
    • Parcel (zh.parceljs.org/)

Basic concepts of Webpack

What is a webpack

Webpack is a concrete solution for front-end project engineering.

Why master Webpack

Webpack makes front-end development more efficient

① Code compression confusion

② Deal with compatibility of JavaScript on the browser side

③ Handle the resources in the project in a modular way

Note: At present, most front-end projects such as Vue/React are developed based on Webpack.

Install the required packages

# Switch mirror source
nrm use taobao
Copy the code
# initialization
npm init -y
Copy the code
Install project dependencies
npm install jquery
Copy the code

Basic use of Webpack

Create interlaced discoloration demo for lists

Objective: To implement the list interlacing color-changing project in a modular way, in preparation for the study of Webpack.

Specific steps:

① In the project directory, create the SRC source directory

② In the project directory, create a public static resource directory

③ Create index.js in SRC directory

Create index. HTML in public directory and add index.js

⑤ Initialize the basic structure of the home page (create structure like ul>li)

⑥ Through ES6 modular way to import jQuery, realize the list interline color effect

import $ from 'jquery';

$(function () {$('li:odd').css('background-color'.'#ccffcc');
  $('li:even').css('background-color'.'#ffccff');
})
Copy the code

Analyze the problems encountered in the project

  • Cause of error:
    • Browser ES6+ advanced syntax support is not good, there are compatibility issues
  • How to solve:
    • Get programmers to write as well as possible during development
    • Keep the browser from “compatibility issues” at runtime
  • Specific plan:
    • Install and configure WebPack in your project to degrade the JS code

Install and configure webPack

Goal:

  • Webpack handles compatibility issues with JS code

Install two webPack-related packages: [email protected] and [email protected]

① In the root directory of the project, create a webpack configuration file named webpack.config.js and initialize the following basic configuration:

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

② Add dev scripts under package.json as follows:

"scripts": {
  "dev": "webpack"
},
Copy the code

③ Run the NPM run dev command in the terminal to start webpack and build the project

Pack the result

After executing the NPM run dev command, the dist folder is generated in the project root and main.js is generated in the dist folder

Main.js is a combination of jquery.js and index.js.

Add main.js to index.html and see what happens.

Optional value of mode

Objective: To know the role of each mode value and the specific application scenario of each value.

The mode node has two optional values, which are:

(1) development

  • The development environment
  • There is no code compression or performance optimization for the generated files from packaging
  • Fast packaging, suitable for use in the development phase

(2) production

  • The production environment
  • The generated files are compressed and optimized for performance
  • Packaging is slow and is only suitable for use during the project release phase

The role of webpack. Config. Js

Webpack. Config. Js is what

  • Webpack.config.js is the webpack configuration file.

role

  • Tell WebPack how to package the project.

The time when it was read

  • When NPM run dev (package time), the configuration file is read before the project is packaged.

Default conventions in WebPack

In webPack 4.x and 5.x versions, there are the following default conventions:

① The default package entry file is SRC -> index.js

The default output file path is dist -> main.js

Note: You can change the default convention for packaging in webpack.config.js

Custom packaging entry and exit

In the webpack.config.js configuration file, specify the entry to the package through the Entry node. Specify the packaged exit through the output node.

Example code is as follows:

const path = require('path');

module.exports = {
  // Package mode
  mode: 'development'.// production development
  // Import file
  entry: path.join(__dirname, 'src'.'index.js'),
  // Export file
  output: {
    path: path.join(__dirname, 'dist'), // Use an absolute path, otherwise an error is reported
    filename: 'bundle.js',}}Copy the code

Rerun NPM run dev to get the new package result bundle.js.

New packaging result bundle.js is introduced in index.html.

Plug-ins in WebPack

An overview of the

What the WebPack plug-in does

By installing and configuring third-party plug-ins, you can extend the power of WebPack and make it easier to use.

The most commonly used WebPack plug-ins are as follows:

(1) the clean – webpack – the plugin

  • Automatically clean up the dist directory each time you pack

(2) webpack – dev – server

  • Similar to the Nodemon tool used in the Node.js phase
  • Whenever the source code is modified, WebPack automatically packages and builds the project

(3) HTML – webpack – the plugin

  • HTML plug-ins in Webpack
  • This plug-in allows you to customize the content of the index.html page

clean-webpack-plugin

Function: Automatically clean up the old files in the dist directory every time you pack a build to ensure that the dist code is up to date.

Install the dependency package: [email protected]

Add configuration to webpack.config.js:

// 1. Configure the automatic cleanup plug-in (at packaging time, the plug-in will automatically clean up the unnecessary files in dist)
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const cleanPlugin = new CleanWebpackPlugin();

module.exports = {
  mode: 'development'.// other items omitted......
  // Plug-in configuration
  plugins: [ cleanPlugin ]
}
Copy the code

Rerun NPM run dev to clean up the dist folder.

webpack-dev-server

The basic use

What it does: You can have WebPack listen for changes to your project’s source code for an automatic package build.

The installation package [email protected]

Configuration webpack – dev – server

Package. json -> scripts dev

"scripts": {
  "dev": "webpack serve"// Serve, not server},Copy the code

② Add the devServer node to the webpack.config.js configuration file to configure the webpack-dev-server plug-in

devServer: {
  port: 9000.// The port number used for real-time packaging
  open: true // Automatically open the browser after the initial packaging
}
Copy the code

③ Run the NPM run dev command again to package the project

4 Visit http://localhost:8080 in the browser to view the automatic packaging effect

Note: if you modify the webpack.config.js configuration file, or modify the package.json configuration file, you must restart the real-time packaging server, otherwise the latest configuration file will not take effect!

Where are the files generated by packaging?

① If webpack-dev-server is not configured, the files generated by webpack are stored on physical disks

  • Strictly follow the configuration specified by the developer in webpack.config.js

  • Store according to the path specified by the output node

② After webpack-dev-server is configured, the generated files are stored in the memory

  • The path specified by the output node is not saved to the actual physical disk

  • Improved performance for real-time packaged output because memory is much faster than physical disk

How can I access files generated in memory?

  • The files generated by webpack-dev-server into memory are placed in the root directory of the project by default and are virtual and invisible.
  • You can directly use/to represent the project root directory, followed by the name of the file to access, you can access the file in memory
  • For example, /bundle.js means to access the bundle.js file generated by webpack-dev-server into memory

Js

html-webpack-plugin

Html-webpack-plugin is an HTML plug-in in Webpack.

What it does: Automatically injects generated bundle.js into HTML pages.

The installation package [email protected]

Configure the html-webpack-plugin in webpack.config.js

const HtmlPlugin = require('html-webpack-plugin');
const htmlPlugin = new HtmlPlugin({
  template: path.join(__dirname, 'public'.'index.html'), // What is your HTML called in public
  filename: 'index.html' // What is the name of the packed HTML (this file will be generated in the dist folder)
});

module.exports = {
  mode: 'development'.// other items omitted......
  // Plug-in configuration
  plugins: [ cleanPlugin, htmlPlugin ]
}
Copy the code

Other notes:

The index. HTML page copied to the root directory of the project through the HTML plugin is also in memory, so it is not visible

The HTML plugin automatically injects the bundle.js file into the generated index.html page

The loader in webpack

Summary of the loader

What is the use of loader?

  • In actual development, WebPack can only package modules with.js extensions by default.
  • Other modules that do not end with.js suffixes cannot be handled by Webpack by default
  • You need to call loader to pack non-JS files normally, otherwise an error will be reported!

Therefore, the loader’s role is to help WebPack process specific file modules. Such as:

  • Css-loader can package files related to.css
  • Less-loader can package files related to processing.less
  • Babel-loader can be packaged to handle advanced JS syntax that WebPack cannot handle

The process of calling loader

Package and process CSS files

① Installation packages [email protected] and [email protected]

Add loader rules to webpack.config.js module -> rules array:

module.exports = {
  mode: 'development'.// other items omitted......
  module: {
    rules: [
      // Process CSS files
      { test: /\.css$/, use: ['style-loader'.'css-loader']},]}}Copy the code

Test indicates the matched file type, and use indicates the loader to be invoked

Note:

  • The loader order specified in the use array is fixed
  • Multiple Loaders are invoked in the following order: from back to front

Package and process less files

① Install [email protected] and [email protected]

Add loader rules to webpack.config.js module -> rules array:

module.exports = {
  mode: 'development'.// other items omitted......
  module: {
    rules: [
      // Process CSS files
      { test: /\.css$/, use: ['style-loader'.'css-loader']},// Process less files
      { test: /\.less$/, use: ['style-loader'.'css-loader'.'less-loader']},]}}Copy the code

Package files associated with the URL path

① Install [email protected] and [email protected]

  • Both modules are in WebPack 4 and are used to work with resources (images, font files, and so on)
  • Both loaders are also available in the latest version of WebPack 5.
  • In the latest version of WebPack 5, assets are used to handle resources.

Add loader rules to webpack.config.js module -> rules array:

module.exports = {
  mode: 'development'.// other items omitted......
  module: {
    rules: [
      // Process CSS files
      { test: /\.css$/, use: ['style-loader'.'css-loader']},// Process less files
      { test: /\.less$/, use: ['style-loader'.'css-loader'.'less-loader']},// Process image files
      { test: /\.(jpg|png|gif)$/, use: 'url-loader? limit=6055&outputPath=images'}}},]Copy the code

Among them? The loader argument follows:

  • Limit specifies the size of the image in bytes.
  • Only images of a size ≤ limit will be converted to Base64 format. > Limit images directly use image files.

The preceding configuration of url-loader can be performed using query parameters. It can also be configured using the format of the object:

module.exports = {
  mode: 'development'.// other items omitted......
  module: {
    rules: [
      // Process CSS files
      { test: /\.css$/, use: ['style-loader'.'css-loader']},// Process less files
      { test: /\.less$/, use: ['style-loader'.'css-loader'.'less-loader']},// Process image files
      { 
        test: /\.(jpg|png|gif)$/, 
        loader: 'url-loader'.// Use object syntax
        options: {
          limit: 10000.If the image is greater than limit, the original image will be used. If the image is less than or equal to limit, base64 will be used
          outputPath: 'images'.// After packing, place the images in the images folder
          name: '[hash:8]_[name].[ext]'.[hash:5] indicates a random 5 character. [name] indicates the name of the original image. [ext] indicates the suffix of the original image
          esModule: false.// Add this to allow CSS to introduce the background image display
        },
        type: 'javascript/auto'.// Add this to allow CSS to introduce the background image display}}},]Copy the code

html-loader

  • NPM install html-loader

  • configuration

    module.exports = {
      mode: 'development'.// other items omitted......
      module: {
        rules: [
          // Process CSS files
          { test: /\.css$/, use: ['style-loader'.'css-loader']},// Process less files
          { test: /\.less$/, use: ['style-loader'.'css-loader'.'less-loader']},// Process image files
          { 
            test: /\.(jpg|png|gif)$/, 
            loader: 'url-loader'.// Use object syntax
            options: {
              limit: 10000.If the image is greater than limit, the original image will be used. If the image is less than or equal to limit, base64 will be used
              outputPath: 'images'.// After packing, place the images in the images folder
              name: '[hash:8]_[name].[ext]'.[hash:5] indicates a random 5 character. [name] indicates the name of the original image. [ext] indicates the suffix of the original image
              esModule: false.// Add this to allow CSS to introduce the background image display
            },
            type: 'javascript/auto'.// Add this to allow CSS to introduce the background image display
          },
          // Process images introduced by the IMG tag in HTML
          { test: /\.html$/, use: 'html-loader'}}}]Copy the code

So much for:

  • You can import images in JS with import
  • You can add background images in the CSS
  • You can import images in HTML via the SRC of img

Asset in webpack5 handles resources

Use asset instead of url-loader, file-loader, and raw-loader.

module.export = {
  output: {
    path: join(__dirname, 'dist'),
    filename: 'bundle123.js'.assetModuleFilename: 'images/[hash:8][ext]'.// Output path of the configuration file
  },
  module: {
    rules: [
      // Process CSS files
      { test: /\.css$/, use: ['style-loader'.'css-loader']},// Process less files
      { test: /\.less$/, use: ['style-loader'.'css-loader'.'less-loader']},// Process image resources
      {
        test: /\.(jpg|png|gif)$/,
        type: 'asset'.parser: {
          dataUrlCondition: {
            maxSize: 12000.// If the image is larger than this size, use the original image, otherwise use the base64 string}}},// Process images introduced by the IMG tag in HTML
      { test: /\.html$/, use: 'html-loader'}}}]Copy the code

base64

  • Base64 format, which is just a string.
  • Comparison with the original picture:
    • The base64 string is about 30% larger than the original image.
    • Using base64 strings can reduce network requests and take the strain off the server.

Conclusion: Base64 format can be used for small graphs in practical development. Use the original image for larger images.

Package handles advanced syntax in JS files

Webpack can only be packaged to handle a portion of advanced JavaScript syntax. For advanced JS syntax that webPack can’t handle, use babel-Loader for packaging.

For example, Webpack cannot handle the following JavaScript code:

// js decorator
function info(target) {
  target.abc = 'Hahahahahahahaha, this is new grammar';
}

// Add an ABC attribute to Person
@info
class Person {}console.log(Person.abc);
Copy the code

Install babel-loader related packages [email protected] and @babel/[email protected] and @babel/[email protected]

In the module -> rules array of webpack.config.js, add the loader rule as follows:

module.exports = {
  mode: 'development'.// other items omitted......
  module: {
    rules: [
      // Process CSS files
      { test: /\.css$/, use: ['style-loader'.'css-loader']},// Process less files
      { test: /\.less$/, use: ['style-loader'.'css-loader'.'less-loader']},// Process image files
      { test: /\.(jpg|png|gif)$/, use: 'url-loader? limit=6055&outputPath=images' },
      //.js files are processed using babel-loader. But don't deal with third-party modules in the node_moduels folder
      { test: /\.js$/, use: 'babel-loader'.exclude: /node_modules/}}}]Copy the code

Configure the Babel – loader

In the project root directory, create a configuration file named babel.config.js and define the following configuration items for Babel:

module.exports = {
  // Declare the plugins available for Babel
  plugins: [['@babel/plugin-proposal-decorators', { legacy: true}}]]Copy the code

Packaging releases

Why package it

After the completion of project development, webpack is needed to package and publish the project, mainly for the following two reasons:

① In the development environment, the files generated by packaging are stored in memory, and the files generated by final packaging cannot be obtained

② In the development environment, the generated files will not be compressed and optimized

In order for the project to run in a production environment with high performance, the project needs to be packaged and released.

Configure the packaged publishing of WebPack

Under the scripts node of package.json file, add the following build command:

"scripts": {
  "dev": "webpack serve"."build": "webpack --mode production"
},
Copy the code
  • — Model is a parameter that specifies the mode in which WebPack will run.
  • Production represents the production environment and performs code compression and performance optimization on the files generated by packaging.

Note: The model option in webpack.config.js is overridden by the parameter specified by –model.

Generate JavaScript files into a js directory

  • In the output node of the webpack.config.js configuration file, do the following:

    output: {
      path: path.join(__dirname, 'dist'),
      filename: 'js/bundle.js'.// Add the js folder here.
    },
    Copy the code

Generate the image file into the image directory

  • Modify the url-loader configuration item in webpack.config.js and add the outputPath option to specify the outputPath of the image file:

    module: {
      rules: [{test: /\.(jpg|png|gif)$/, use: 'url-loader? limit=6055&outputPath=images']}},Copy the code

Source Map

Current problems

  • Error line numbers do not match in the development environment. For example, an error was reported at line 23, but the browser prompts an error at line 20.
  • After packaging, we don’t want our code to be seen by others.

SourceMap can solve these problems.

What is a Source Map

A Source Map is an information file that stores location information.

In other words, the Source Map file stores the position of the compressed and obfuscated code before the transformation.

With it, when an error occurs, the debugging tool will directly display the original code, rather than the converted code, which can greatly facilitate later debugging.

configuration

The development environment

It is recommended to add the following configuration to webpack.config.js to ensure that the number of error lines is consistent with the number of lines in the source code:

module.exports = {
  // Source-map is only available in development mode
  // (in the development, the programmer needs to fix the error line number accurately)
  devtool: 'source-map',}Copy the code

The production environment

module.exports = {
  // Nosource-source-map is suitable for production environments.
  // (in production environment, we do not want others to see our source code, this configuration item only shows the line number, but does not show the source code)
  devtool: 'nosources-source-map',}Copy the code

conclusion

In actual development, Vue scaffolding will be used to generate projects with Webpack, out of the box, but the basic concepts still need to be understood!