Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

webpack 5 有哪些新功能 #64

Open
nmsn opened this issue May 24, 2023 · 1 comment
Open

webpack 5 有哪些新功能 #64

nmsn opened this issue May 24, 2023 · 1 comment
Labels

Comments

@nmsn
Copy link
Contributor

nmsn commented May 24, 2023

No description provided.

@nmsn nmsn added the webpack label May 24, 2023
@nmsn
Copy link
Contributor Author

nmsn commented May 24, 2023

原文地址:https://zhuanlan.zhihu.com/p/348612482

总结

构建时新特性

  • 内置静态资源构建能力 —— Asset Modules
  • 内置 FileSystem Cache 能力加速二次构建
  • 内置 WebAssembly 编译及异步加载能力(sync/async)
  • 内置 Web Worker 构建能力

运行时新特性

  • 移除了 Node.js Polyfills,Polyfill 交由开发者自由控制
  • 资源打包策略更优,构建产物更“轻量”
  • 深度 Tree Shaking 能力支持
  • 更友好的 Long Term Cache 支持性,chunkid 不变
  • 支持 Top Level Await,从此告别 async

详细描述

内置静态资源构建能力 —— Asset Modules

在 Webpack5 之前,我们一般都会使用以下几个 loader 来处理一些常见的静态资源,比如 PNG 图片、SVG 图标等等,他们的最终的效果大致如下所示:

  • raw-loader:允许将文件处理成一个字符串导入
  • file-loader:将文件打包导到输出目录,并在 import 的时候返回一个文件的 URI
  • url-loader:当文件大小达到一定要求的时候,可以将其处理成 base64 的 URIS ,内置 file-loader

Webpack5 提供了内置的静态资源构建能力,我们不需要安装额外的 loader,仅需要简单的配置就能实现静态资源的打包和分目录存放。如下:满足规则匹配的资源就能够被存放在 assets 文件夹下面。

// webpack.config.js
module.exports = {
    ...,
    module: {
      rules: [
          {
            test: /\.(png|jpg|svg|gif)$/,
            type: 'asset/resource',
            generator: {
                // [ext]前面自带"."
                filename: 'assets/[hash:8].[name][ext]',
            },
        },
      ],
    },
}

其中 type 取值如下几种:

  • asset/source ——功能相当于 raw-loader。
  • asset/inline——功能相当于 url-loader,若想要设置编码规则,可以在 generator 中设置 dataUrl。
  • asset/resource——功能相当于 file-loader。项目中的资源打包统一采用这种方式,得益于团队项目已经完全铺开使用了
    HTTP2 多路复用的相关特性,我们可以将资源统一处理成文件的形式,在获取时让它们能够并行传输,避免在通过编码的形式内置到 js 文件中,而造成资源体积的增大进而影响资源的加载。
  • asset—— 默认会根据文件大小来选择使用哪种类型,当文件小于 8 KB 的时候会使用 asset/inline,否则会使用 asset/resource。也可手动进行阈值的设定。

内置 FileSystem Cache 能力加速二次构建

Webpack5 之前,我们会使用 cache-loader 缓存一些性能开销较大的 loader ,或者是使用 hard-source-webpack-plugin 为模块提供一些中间缓存。在 Webpack5 之后,默认就为我们集成了一种自带的缓存能力(对 module 和 chunks 进行缓存)。通过如下配置,即可在二次构建时提速。

// webpack.config.js
module.exports = {
    ...,
    cache: {
        type: 'filesystem',
        // 可选配置
        buildDependencies: {
            config: [__filename],  // 当构建依赖的config文件(通过 require 依赖)内容发生变化时,缓存失效
        },
        name: '',  // 配置以name为隔离,创建不同的缓存文件,如生成PC或mobile不同的配置缓存
        ...,
    },
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant