preface

Hello everyone, I am Xiaolang, this time I bring you a summary of my previous learning of how to use Webpack, I hope to help friends in need, there are a lot of things in school, so I haven’t posted in Nuggets for a long time. To have a holiday, continue to study, brush to Lin Sanxin B station video, Sanxin big man he wrote his own article and then to share with others, is a fast learning way, I think it is also very correct for me, while sharing their own impression will be deep

Webpack introduction:

Webpack is one of the mainstream front-end engineering solutions

Main features: it provides friendly front-end modular development support, as well as code compression and confusion, handling browser side JavaScript compatibility, sexual optimization and other powerful features.

Benefits: Let programmers focus on the implementation of specific functions, improve front-end development efficiency and project maintainability. Note: At present, Vue, React and other front-end projects are basically engineering development based on Webpack

preparation

The installation

To install webpack + webpack-cli in your project, use -d equivalent to –save-dev

-d adds devDependencies to package.json, which we use only during development

-s is equivalent to –save written to the Dependencies object, which is used by both the development environment and production

If your project doesn’t have package.json, use NPM init -y to quickly configure it

NPM install [email protected] [email protected] -dCopy the code
 "devDependencies": {
    "webpack": "^ 5.42.1"."webpack-cli": "^ 4.9.0"
 }
Copy the code

Configuring Startup Commands

Configure scripts in package.json

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

From the command line we use NPM run dev to start the webpack command

The basic use

Create the webpack.config.js file

In the project root directory, create a WebPack configuration file called webpack.config.js, which WebPack reads to package the project based on the given configuration before actually starting the package build.

Set the mode

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

The mode values are as follows:

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

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

Set up entrances and exits

Default conventions in Webpack 4.x and 5.x:

  • The default entry file issrc -> index.js
  • Default output filedist -> main.js

We can customize it in webpack.config.js

Entry: The entry for packing

Output: packaged export

We can set it as follows

module.exports = {
  entry: './src/index.js'.// Package the entry file path
  output: './dist/mian.js'.// Output file path
}
Copy the code

Better yet, use the path module to concatenate paths

const path = require('path')
module.exports = {
  mode: 'development'.entry: path.join(__dirname, './src/index.js'), // Package the entry file path
  output: {
    path: path.join(__dirname, './dist'), // Output file path
    filename: 'js/bundle.js'.Dist /js/bundle.js/dist/js/bundle.js}},Copy the code

Webpack-dev-server is easy to use

When the source code is modified, WebPack automatically packages and builds the project, so you don’t have to go to NPM run Dev every time

Webpack-dev-server provides a hot update development server

The installation

NPM install [email protected] - DCopy the code

Once installed, you can start it from WebPack Serve

configuration

To facilitate webpack-dev-server startup we add a new command to package.json scripts

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

There are many options for devServer to configure ports in webpack.config.js, and I’ll configure one port here

module.exports = {
  devServer: {
    port: 8080,}}Copy the code

DevServer.com press, enable gzip compression.

Devserver.contentbase, which tells the server where to provide content. Only if you want to provide static files.

Devserver. host specifies host. Use 0.0.0.0 to make it accessible on the LAN.

Devserver. hot, enabling webPack’s hot Module Replacement.

Devserver. hotOnly, whether it is not allowed to fall back to using the refresh page when the build fails.

Devserver. inline, mode switch. The default mode is inline. Use false to switch to iframe mode.

Devserver. open: whether to open the home page using a browser after starting webpack-dev-server.

Devserver. overlay, whether to allow display of compilation errors using full screen overlay. Default disallow

Devserver. port, the listening port number. The default of 8080.

Devserver.proxy, the proxy, is suitable for a separate back-end development server API.

Devserver. publicPath, which sets the output directory of the packaged files in memory. Different from output.publicPath.

After modification, use NPM Run Serve to package the project

When the packaging is complete, a real-time packaging HTTP server is launched, prompting us to visit http://localhost:8080/, after which we can see the effect of our page

Packaged file

The files generated by packaging are stored in memory. Because memory is faster and improves the performance of real-time packaging, the output path set above is for the webpack-dev-server is not installed

How do we access bundel.js packaged, since webpack-dev-server starts a server, / is the root directory of the project, and we can access bundle.js directly from the address bar

Plug-in plugin

Webpack can be extended to make it more powerful by installing and configuring third-party plug-ins

html-webpack-plugin

This plugin is used a lot. By inserting common CSS and JS files into the HTML, you can reduce the number of requests and optimize the content of the index.html page through this plugin.

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

The installation

NPM install [email protected] - DCopy the code

configuration

Do this in plugins in webpack.config.js

var HtmlWebpackPlugin = require('html-webpack-plugin') / / 1. The guide
const path = require('path')
module.exports = {
  / /...
  // Use HtmlWebpackPlugin in the plugin
  plugins: [
    new HtmlWebpackPlugin({
      template: path.join(__dirname, './src/index.html'), // Original file path
      filename: path.join(__dirname, './dist/index.html'), // Output file path})],}Copy the code

HtmlWebpackPlugin has many optional parameters, and I’ll just mention the following three commonly used ones

Title: The title of the generated HTML document. Configure this item, which does not replace the contents of the title element in the specified template file

Template: the location of a local template file that supports loaders (e.g. Handlebars, EJS, undersore, HTML, etc.)

Filename: indicates the name of the output file. The default value is index. HTML. In addition, you can specify directory locations for output files (for example, ‘./dist/index.html’)

use

Run the command NPM run dev to see that the packaging is complete

If we use NPM Run serve, we will not have these two, but both in memory, we can use the address bar to view

clean-webpack-plugin

Automatically clean up old files in the dist directory

The installation

NPM install [email protected] - DCopy the code

configuration

Do this in plugins in webpack.config.js

const { ClenWebpackPlugin } = require('clean-webpack-plugin') / / introduction
module.exports = {
  / /...
  plugins: [
    new ClenWebpackPlugin(), // Mount the create plug-in instance],}Copy the code

Loader loader

The non-.js suffix module Webpack cannot process JavaScript and JSON files by default, and needs to call the loader to pack properly

The loader is used to export JavaScript modules as functions. Such as:

  • Css-loader packages. Css-related files
  • Less-loader Packages files related to. Less
  • Babel-loader packages advanced JS syntax that WebPack can’t handle

Loader Invocation process

Packaging CSS

The installation

NPM I [email protected] [email protected] -dCopy the code

configuration

In the command, test indicates the matched file type (using the re), and use indicates the loader to be invoked.

  • useArray specified inloaderThe order is fixed
  • loaderCall order: from right to left

Do this in the module of webpack.config.js

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

Pack less

The installation

NPM I [email protected] [email protected] -dCopy the code

configuration

Do this in the module of webpack.config.js

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

Other CSS packaging processes also install the specified loader

The packaged file

Loader in addition to CSS packaging, we use file-loader url-loader can also handle the image referenced by URL

The installation

NPM I [email protected] [email protected] -dCopy the code

configuration

Do this in the module of webpack.config.js

module.exports = {
  / /...
  module: {
    rules: [{test: /\.jpg|png|gif$/,
        use: {
            loader: 'url-loader'.options: {
                limit: 77777.outputPath: 'image',}}},],},}Copy the code

Options is a loader parameter:

Limit specifies the size of an image, in bytes. Only images whose size is ≤ limit are converted to Base64

Dist /image outputPath: specifies the storage folder dist/image to generate image files in the image directory

Babel-loader is simple to use

Use babel-loader to package advanced syntax in JS

The installation

NPM I [email protected] @babel/[email protected] @babel/[email protected] -dCopy the code

configuration

Do this in the module of webpack.config.js

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

Note: Use exclude to exclude /node_modules/

In the project root directory, create the babel.config.js file for configuration

Declare the plug-ins available for Babel

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

Packaging releases

The resulting files are packaged in the development environment without code compression or performance optimization and are stored in memory, so they are packaged and distributed in the production environment

Add it to the scripts of package.json

"scripts": {
    "build": "webpack --mode production",},Copy the code

After that, NPM run build was directly packaged and released. This –model stands for production environment, and the generated files were compressed and optimized for performance. This overrides the model option in webpack.config.js

Webpack creates the Vue project

In fact, we use VUE – CLI and Vue UI to build vUE project Webpack have helped us to configure, here I introduce how to use Webpack to create vue project.

Initialize the project directory

Initialize package.json after the project folder is created

npm init -y
Copy the code

Create the webpack configuration file webpack.config.js in the root directory of the project. In real development, there are development and production environments.

Index.js: entry file

Index.html: entry file template

Babel.config. js: Babel configuration file

The project structure is as follows:

Project_name | - SRC │ | -- index. Js | | - App. Vue | -- index. HTML | -- package. Json | -- webpack. Config. Js | - babel.config.jsCopy the code

Installation configuration webPack related

Install the webpack webpack-cli webpack-dev-server dependency

NPM install [email protected] [email protected] [email protected] -dCopy the code

Configuration package. Json

"scripts": {
    "dev": "webpack"."serve": "webpack-dev-server --open --hot"."build": "webpack --mode=development --progress --hide-modules",},Copy the code

Configuration webpack. Config. Js

const path = require('path')

module.exports = {
  mode: 'development'.entry: path.join(__dirname, './src/index.js'), // Package the entry file path
  output: {
    path: path.join(__dirname, './dist'), // Output file path
    filename: 'js/bundle.js'.Dist /js/bundle.js/dist/js/bundle.js
  },
  devServer: {
    contentBase: path.join(__dirname, './dist'),
    port: 8080.// Start port}},Copy the code

Install the configurationVuerelated

Vue -loader vUE – template-Compiler is used to install vUE

npm install vue-loader vue-template-compiler -D 
Copy the code

Install a VUE if the project doesn’t have one

npm install vue
Copy the code

Configuration webpack. Config. Js

Be careful to introduce the VueLoaderPlugin

const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
 / /...
 module: {
      rules: [
      / /... Other rules
      {
          test: /\.vue$/,
          loader: 'vue-loader'}},plugins: [
      new VueLoaderPlugin()
  ]
}
Copy the code

Installing a plug-in

The html-webpack-plugin and the clean-webpack-plugin, both of which we’ve covered above

The installation

NPM install [email protected] [email protected] -dCopy the code

Configuration webpack. Config. Js

/ /...
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
    / /...
	plugins: [
		new HtmlWebpackPlugin({
     		template:'./index.html',}).new CleanWebpackPlugin(),
	],
 };
Copy the code

Install loader

Style-loader, CSS-loader, file-loader, url-loader, etc. We have introduced the above. If you need sASS, less loader can be installed by itself, here I install Sass

NPM install [email protected] [email protected] [email protected] [email protected] sass-loader node-sass -dCopy the code

Configuration webpack. Config. Js

Sass will exclude node_modules

/ /...

module.exports = {
	/ /...
    module: {
        rules: [{test: /\.css$/,
                use: [
                    'style-loader'.'css-loader'] {},test: /\.jpg|png|gif$/,
            use: {
                loader: 'url-loader'.options: {
                    limit: 77777.outputPath: 'image',}}}, {test: /\.sass$/,   
              use:['vue-style-loader'.'css-loader'.'sass-loader'].include: path.resolve(__dirname + '/src/'),    
              exclude: /node_modules/}}},]Copy the code

Install the bable

I’m going to install a couple of common ones here

npm install  babel-loader @babel/core @babel/cli @babel/preset-env -D
npm install  @babel/runtime @babel/plugin-transform-runtime -D
npm install  @babel/plugin-transform-arrow-functions -D
Copy the code

Configuration webpack. Config. Js

Again, exclude node_modules as above

/ /...

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

Configure the Babel. Config. Js

module.exports = function (api) {
    api.cache(true);
  
    const presets = [
        '@babel/preset-env',];const plugins = [
        '@babel/plugin-transform-arrow-functions'.'@babel/plugin-transform-runtime'
    ];
  
    return {
      presets,
      plugins
    };
  }
Copy the code

Finally, we can start the VUE project with NPM Run Serve

Past highlights:

Get a quick start on Electron and have your own desktop app

Can’t Vue3 yet? A quick introduction to notes

Not TS yet? Get you started with TypeScript quickly

Quick start Vuex to easy writing Vuex

From understanding to in-depth virtual DOM and implementation of diff algorithm

Write a simple VUE response to take you to understand the principle of response

From using it to implementing your own simple Vue Router look at this

The essential basics of the front-end interview, although little but you can’t help but know