[ Webpack 知识体系 | 青训营笔记 ]

81 阅读3分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 22 天

Webpack是一个前端模块打包器,它可以将JavaScript,CSS,图像等资源打包为单个文件,以便于在浏览器端进行加载。本文将介绍Webpack的知识体系,并以代码与文字相结合的方式进行阐述。

基本概念

入口(entry)

入口是指Webpack打包的起点,它告诉Webpack从哪里开始打包。

module.exports = {
  entry: './src/index.js'
};

出口(output)

出口是指Webpack打包的终点,它告诉Webpack最终生成的文件存放在哪里。

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  }
};

Loaders

Loaders是Webpack的核心,它负责将非JavaScript文件转换为JavaScript文件,便于Webpack打包。

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  }
};

Plugins

Plugins是Webpack的扩展,它可以帮助我们实现各种功能,如代码压缩,生成HTML文件等。

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
}
]
},
plugins: [
    new HtmlWebpackPlugin({
        template: './src/index.html'
    })
]};

Mode

Mode是Webpack的运行模式,它有两种模式:生产模式(production)和开发模式(development)。

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  mode: 'development'
};

Loaders的使用

在Webpack中,Loaders可以帮助我们实现各种功能,如将CSS文件转换为JavaScript文件,将图像文件转换为Base64编码等。以下是常用的Loaders的使用方法。

  • CSS Loader

CSS Loader可以将CSS文件转换为JavaScript文件,并在浏览器端通过JavaScript代码进行加载。

javascriptCopy code
module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  }
};
  • URL Loader

URL Loader可以将图像文件转换为Base64编码,并在浏览器端通过JavaScript代码进行加载。

javascriptCopy code
module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /.(png|jpg|jpeg|gif)$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 8192
          }
        }
      }
    ]
  }
};

Plugins的使用

在Webpack中,Plugins可以帮助我们实现各种功能,如打包优化,资源管理,代码压缩等。以下是常用的Plugins的使用方法。

HtmlWebpackPlugin

HtmlWebpackPlugin可以帮助我们自动生成HTML文件,并将打包后的JavaScript文件自动插入到HTML文件中。

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'
    })
  ]
};

CleanWebpackPlugin

CleanWebpackPlugin可以帮助我们自动清理构建目录中无用的文件,以保证构建目录中只包含当前构建的文件。

const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  plugins: [
    new CleanWebpackPlugin()
  ]
};

UglifyjsWebpackPlugin

UglifyjsWebpackPlugin可以帮助我们对JavaScript代码进行压缩,以节省浏览器加载的时间。

const UglifyjsWebpackPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  plugins: [
    new UglifyjsWebpackPlugin()
  ]
};

Webpack的优化

Webpack的优化可以通过以下几种方式实现:

Tree Shaking

Tree Shaking是Webpack的一项特性,它可以帮助我们去除JavaScript代码中未被使用的部分,从而节省加载的时间。Tree Shaking的实现需要在ES6模块的基础上进行,因为ES6模块是静态的,可以在编译时判断哪些代码是被使用的,哪些代码是未被使用的。下面是一个使用Tree Shaking的例子

// util.js
export function square(x) {
  return x * x;
}

export function cube(x) {
  return x * x * x;
}

// index.js
import { square } from './util.js';

console.log(square(5)); // 25

在上面的例子中,我们只引用了util.js中的square函数,因此在打包后的JavaScript文件中不会包含cube函数。

  • Code Splitting

Code Splitting是Webpack的另一项特性,它可以将我们的JavaScript代码拆分为多个文件,从而让浏览器可以并行加载这些文件,提高加载速度。

Code Splitting的实现可以通过使用import()语法实现,下面是一个使用Code Splitting的例子:

javascriptCopy code
button.addEventListener('click', () => {
  import('./dialog.js')
    .then(dialog => {
      dialog.open();
    })
    .catch(err => {
      console.log(err);
    });
});

在上面的例子中,当用户点击按钮时,我们才会加载dialog.js文件,从而实现Code Splitting。

Lazy Loading

Lazy Loading可以帮助我们控制JavaScript代码的加载时机,从而提高页面的加载速度。

Lazy Loading的实现与Code Splitting类似,也可以使用import()语法实现。