Basic use of webpack packaging tools

Table of contents

1. What is webpack?

Two, the basic use of webpack

1. Initialize the project

2. Install webpack and its dependencies

3. Use

3.1 Configure webpack:

3.2 Add packaging commands to the package.js file

3.3 Execute the packaging command

3. Webpack related plug-ins

Plugin 1: HtmlWebpackPlugin

Plugin 2: BundleAnalyzerPlugin

 Plugin 3: splitChunks

4. Modular packaging of non-js files 


1. What is webpack?

webpack is a modular packaging tool. We usually develop in a modular way when developing, but browsers support modularity very little, so we need to use the webpack packaging tool to package modular codes to generate browser-supported specifications. Simply put, webpack is used to package project modular files to generate common script files, and then introduce them into html files.

Two, the basic use of webpack

1. Initialize the project

Execute the following command to generate the default package.json file in the project folder

npm init -y

2. Install webpack and its dependencies

cnpm i webpack webpack-cli --save-dev

3. Use

We create a new src folder under the project folder, and then create three js files under src, namely a.js, b.js, and main.js, of which main.js is used as the entry file.

 We use the qs tool library in a.js and the lodash tool library in b.js. We need to install qs and lodash first:

cnpm i qs lodash -S

a.js

import qs from 'qs'

let obj = {
  name: 'zhangsan',
  age: 12
}

export default {
  url: "/user/login",
  data: qs.stringify(obj)
}

b.js

import _ from 'lodash'

let obj = {
  name: "lisi",
  age: 15
}

export default _.cloneDeep(obj)

Import a.js and b.js in main.js and use:

import a from './a'
import b from './b'

let dom = document.createElement('div')
dom.innerText = JSON.stringify(a)
document.body.appendChild(dom)

let dom2 = document.createElement('div')
dom2.innerText = JSON.stringify(b)
document.body.appendChild(dom2)

If we directly import these three js files into our html file at this time, it will not be usable, because browsers do not support ES6 modularization (import, export), so we need to use webpack to package and generate these three js files Ordinary script files are then imported into html files for use:

3.1 Configure webpack:

Create a new webpack.config.js file under our project folder

webpack.config.js

// 导入path模块,用于处理文件和目录的路径
const path = require('path')
module.exports = {
  //提供 mode 配置选项,告知 webpack 使用development(开发)模式的内置优化
  mode: 'development',
  // 入口文件 (注意:入口使用相对路径)
  entry: './src/main.js',
  // 打包完成后输出到哪个文件 
  output: {
    // 输出文件的路径
    // __dirname表示当前文件模块所属的绝对路径
    // path.resolve() 用来拼接路径
    path: path.resolve(__dirname, 'dist'),
    // 输出文件的文件名
    filename: 'bundle.js',
    // 每次打包都重新生成
    clean: true
  }
}

3.2 Add packaging commands to the package.js file

"build": "webpack --config webpack.config.js"

3.3 Execute the packaging command

npm run build

After the packaging is complete, a dist folder will be generated, under which there is a bundle.js file:

 At this point, we create a new index.html file under the dist folder, import the bundle.js file, and then run the index.html file:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script src="./bundle.js"></script>
</body>
</html>

3. Webpack related plug-ins

Plugin 1: HtmlWebpackPlugin

Since we set clear: true in the export (output), every time we change the code and repackage the project, the dist folder will be cleaned up and a new packaged file will be generated, and our html file will also be cleaned up Therefore, we need to rebuild an html file every time we pack it, and using the HtmlWebpackPlugin plug-in no longer requires us to rebuild an html file every time after packing, because this plug-in will automatically generate an html file for us.

Install the plugin HtmlWebpackPlugin

cnpm install --save-dev html-webpack-plugin

use plugin

webpack.config.js

const path = require('path')
// 导入插件
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
  mode: 'development',
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    clean: true
  },
  // 使用插件
  plugins:[new HtmlWebpackPlugin()],
}

Plugin 2: BundleAnalyzerPlugin

This is a visual graphics plug-in used to analyze the size of modules. It is usually used for front-end performance optimization. For example, through visualization, we can know which file is larger after packaging, and we can divide large files into small modules. At the same time, Mistakenly introduced third-party dependencies can be removed.

Install the plugin BundleAnalyzerPlugin

cnpm i --save-dev webpack-bundle-analyzer

use plugin

webpack.config.js

const path = require('path')
// 导入插件
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
  mode: 'development',
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    clean: true
  },
  // 使用插件
  plugins:[new HtmlWebpackPlugin(),new BundleAnalyzerPlugin()],

}

 Plugin 3: splitChunks

This plugin is used to extract public repeated dependencies and place them in a single script file to optimize front-end performance.

This plugin comes with webpack and does not need to be installed.

Use the plugin:

webpack.config.js

const path = require('path')
module.exports = {
  // 可以设置多个入口文件 
  entry:{
    home:'./src/home.js',
    main:'./src/main.js'
  },
  output:{
    path:path.resolve(__dirname,'dist'),
    // [name]是原先文件的名字
    filename:'bundle_[name].js',
    clean:true
  },
  // 使用插件
  optimization:{
    splitChunks: {
      chunks: 'all',
    }
  }
}

4. Modular packaging of non-js files 

Pack css files

Install the conversion tool:

cnpm i css-loader style-loader --save-dev

Use:
webpack.config.js

const path = require('path')
module.exports = {
  mode: 'development',
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    clean: true
  },
  // 可以设置非js文件的转换规则
  module:{
    rules:[
      // 设置css文件转换规则
      {
        // 正则表达式匹配以.css结尾的文件
        test:/\.css$/,
        // 转换使用的工具
        use:['style-loader','css-loader']
      }
    ]
  }
}

Guess you like

Origin blog.csdn.net/lq313131/article/details/127196532