Chuyển đến nội dung

Bài 14 · Plugins and Assets

Asset Modules: Images, Fonts and Files

Handle images, fonts, SVG and text files with Webpack 5 asset modules: asset/resource, asset/inline, asset/source and the automatic asset type, size limits, generator filenames and CSS url().

Real apps import images, fonts, icons, videos and text files. Before Webpack 5 you installed file-loader, url-loader and raw-loader for these jobs. Webpack 5 has them built in as asset modules: you set a type on a rule and no extra package is needed.

The four asset types

type What you get from the import Typical use
asset/resource a URL to a separate emitted file large images, fonts, PDFs
asset/inline a data URI (base64) inside the bundle tiny icons
asset/source the file's text as a string .txt, SVG source, shaders
asset resource or inline, chosen by size mixed images
JavaScript
module.exports = {
  module: {
    rules: [
      { test: /\.(png|jpe?g|gif|webp|avif)$/i, type: 'asset' },
      { test: /\.svg$/i, type: 'asset/resource' },
      { test: /\.(woff2?|ttf|otf)$/i, type: 'asset/resource', generator: { filename: 'fonts/[name].[hash:8][ext]' } },
      { test: /\.txt$/i, type: 'asset/source' },
    ],
  },
};

Using them in JavaScript

JavaScript
import logo from './logo.png';        // 'logo.3f9a1c2b.png' (a URL string)
import notes from './notes.txt';      // the file text

const img = new Image();
img.src = logo;
document.body.append(img);

The import gives you a URL, not the pixels. Webpack copies the file to dist with a content-hashed name and returns that URL (prefixed with publicPath). Because the name contains a hash, you can cache it forever.

You can also reference files without an import using the new URL pattern, which Webpack understands statically:

JavaScript
const iconUrl = new URL('./icons/star.svg', import.meta.url);

In CSS, url() references go through the same rules automatically (CSS and Style Loaders).

The size threshold for type asset

The plain asset type decides per file: files below a size limit are inlined as data URIs (saving an HTTP request), larger ones become separate files. The default limit is 8 KB; you can change it.

JavaScript
{
  test: /\.(png|jpe?g)$/i,
  type: 'asset',
  parser: { dataUrlCondition: { maxSize: 4 * 1024 } }, // 4 KB
}

Inlining is base64, which makes the data about 33% larger, and it also bloats your JS or CSS. With HTTP/2 and HTTP/3 extra requests are cheap, so keep the threshold small.

Node.js Stand-in: resource or inline?

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Naming emitted files

Set assetModuleFilename once in output, or override per rule with generator.filename:

JavaScript
output: { assetModuleFilename: 'assets/[name].[contenthash:8][ext]' },

[ext] already includes the dot. Group by kind with different folders per rule so the dist folder stays readable. For a CDN, combine this with publicPath: 'https://cdn.example.com/'.

SVG: file or component

You have choices for SVG. As asset/resource you reference it from <img src> or CSS (cached, but you cannot style its inside with CSS). As asset/source you get the markup text to insert into the page. To use SVGs as React components, add a loader such as @svgr/webpack in front, with the issuer condition so it only applies to JS imports:

JavaScript
{
  test: /\.svg$/i,
  issuer: /\.[jt]sx?$/,
  use: ['@svgr/webpack'],
},

Responsive images and other loaders

Asset modules copy files as they are. To resize or recompress images, add image-minimizer-webpack-plugin (with sharp or imagemin), which runs over the emitted assets, or use a responsive-image loader that produces several sizes. Modern formats (WebP, AVIF) are usually worth generating, but measure the result.

Node.js Stand-in: the asset/source and URL results

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Fonts: preload what matters

Fonts imported from CSS become asset/resource files. Browsers only discover them after the CSS is parsed, so important fonts may need <link rel="preload" as="font" crossorigin>. HtmlWebpackPlugin does not add this by default; teams add the tag from a template or a small plugin. Always serve fonts with CORS headers if they come from another origin.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does import logo from './logo.png' give you with type asset/resource?

    The file is copied to the output and the import evaluates to its URL.
  2. 2. Which type returns the file content as text?

    asset/source exports the raw source string.
  3. 3. What does type asset do with a 3 KB PNG using default settings?

    Files below the maxSize threshold are inlined, larger ones are emitted.
  4. 4. Which loaders did asset modules make unnecessary in Webpack 5?

    The built-in asset types replace those three.

Summary

  • Asset modules are built in: asset/resource (URL), asset/inline (data URI), asset/source (text) and asset (automatic).
  • Imports give URLs or strings; emitted files get content-hashed names.
  • parser.dataUrlCondition.maxSize controls the inline threshold; base64 inflates size by about a third.
  • Use output.assetModuleFilename or generator.filename to organize output; combine with publicPath for CDNs.
  • Use issuer and loaders such as SVGR for SVG components; add an image minimizer plugin for optimization.

Next: Define, Copy and Clean Plugins

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.