This is the 28th day of my participation in the August Text Challenge.More challenges in August

The previous three articles discussed how webpack loads other resources, mainly how to load image resources, there are two types of loader to choose from. One is file-loader and the other is url-loader. Compared with file-loader, url-loader has a limit and determines whether to encode base64 based on the size of the current file. If base64 encoding, then encoding base64 characters will be directly with the page request down; Otherwise, use file-loader to package images into image files, and then make separate HTTP requests for each image file.

However, file-loader and url-loader were common ways to handle other resources before WebPack 5, and since WebPack 5, we can actually use a different way to handle other resources.

Before entering the main body, let’s make a clarification:

  • Perform in front of thenpm run buildWhen packing, we have to manually pack the last one before repackingbuildDelete folder, is there a way to make it automatically delete when packing?
    • Yes, we’ll get to that later;

Preparation:

  1. will03_webpack handles other resourcesRename the directory to03_webpack handles other resources 1And delete the insidenode_modulesbuildFolder,;
  2. in01_learn_webpackMake a copy under the directory03_webpack handles other resources 1, and rename it as04_webpack handles other resources 2;
  3. Open theVS CodeTerminal, switch directory to04_webpack handles other resources 2Run,npm installInstall dependencies required by the current project;

1 Asset Modules typeThe introduction of

  • The one we currently usewebpackVersion iswebpack 5:
    • inwebpack 5Before, we used toraw-loader(You can import files as strings),url-loader,file-loadertheseloaderLoad resources;
    • inwebpack 5After that, we can use the ** resource module type (Asset Modules type) ** instead of the aboveloader;
  • Resource module type (Asset Modules type) by adding4The new module type replaces all of thisloader:
    • asset/resourceIssue a separate file and export itURL. Previously by usingfile-loaderImplementation;
    • asset/inlineTo export a resourcedata URI. Previously by usingurl-loaderImplementation;
    • asset/sourceExport the source code of the resource. Previously by usingraw-loaderImplementation;
    • assetI’m exporting adata URIAnd sending a separate file automatically. Previously by usingurl-loaderAnd configure the resource size limit implementation.

2 Asset Modules typeThe use of

Now that file-loader and url-loader can be replaced with resource module types in WebPack 5, we don’t need to use them in the future, so we can uninstall them in the project:

npm uninstall file-loader url-loader
Copy the code

Then, go to the wk.config.js file and find the previous rule that matched the image file:

{
  test: /\.(png|jpe? g|gif|svg)$/,
  use: [
    {
      // loader: 'file-loader',
      loader: 'url-loader'.options: {
        name: 'img/[name].[hash:6].[ext]'.limit: 100 * 1024}}}]Copy the code

Make a simple change as follows:

{
  test: /\.(png|jpe? g|gif|svg)$/,
  type: 'asset/resource' // Equivalent to file-loader
}
Copy the code

Then run the NPM run build command and the package is ready. By default, the image is packaged in the root of the output directory:

How can you customize the output path and file name of the file (like the previous file-loader, you specify the location of the file and put all the images in one folder)? There are two ways:

  1. Set for all resource modules. Configure assetModuleFilename in the top-level output, for example if you want to put all resource modules in the IMG directory:

    module.exports = {
      // ...
      output: {  
        // ...
        assetModuleFilename: 'img/[name].[hash:6][ext]'
      }
      // ...
    }
    Copy the code

    It also works for a project, but not for a placeholder like the example of [ext] in file-loader, it will not be used when the extension is displayed with a.

    After the configuration, delete the build directory in the project directory and run NPM run build. The result is as follows:

  2. Set separately for a rule of the module. Configuration Rule. The generator. The filename:

    {
      test: /\.(png|jpe? g|gif|svg)$/,
      type: 'asset/resource'.// Equivalent to file-loader
      generator: {
        filename: 'img/[name].[hash:6][ext]'}}Copy the code

    Configuration after the first remove project build directory in the directory, and then to run the NPM run the build, results and configure the output above. AssetModuleFilename after the result is the same.

If you want to implement urL-loader, you can set the rule as follows:

{
  test: /\.(png|jpe? g|gif|svg)$/,
  type: 'asset/inline' // Equivalent to url-loader
}
Copy the code

Note: Since it is asset/inline, the resource’s data URI is exported instead of a separate file, so there is no need to configure rule-generator.filename.

After the configuration, delete the build directory in the project directory and run NPM run build. The result is as follows:

For asset/source, it can be used to export TXT files or JSON files. As mentioned in url-loader, if a resource is large, you can package it into a separate file. If a resource is small, you can package it into a separate file to make a separate request. In this case, you can convert it into base64 encoding. For resource module types, to fulfill this requirement (url-loader limit effect), you can set the resource module type to asset type:

{
  test: /\.(png|jpe? g|gif|svg)$/.// type: 'asset/resource', // equivalent to file-loader
  // type: 'asset/inline', // equivalent to url-loader
  type: 'asset'.generator: {
    filename: 'img/[name].[hash:6][ext]'
  },
  parser: {
    dataUrlCondition: {
      maxSize: 100 * 1024 // 100kb}}}Copy the code

That is, if the size of a resource is less than 100KB, it is treated as asset/inline (export the resource’s data URI), otherwise it is treated as asset/ Resource (package into a separate file and export the URL).

After the configuration, delete the build directory in the project directory and run NPM run build. The result is as follows:

As you can see, the image larger than 100KB has been packaged separately, while the image smaller than 100KB has been packaged as base64 encoding into the bundle.js file.

Summary: In Webpack 5, we don’t need to install file-loader and url-loader separately. We can use Asset Modules Type provided by WebPack 5.