isCommonAssetRequest

检查请求是否为通用资源请求。

调用签名

¥Call signature

function isCommonAssetRequest(request: Request): boolean

delay.ts

Source code for the `isCommonAssetRequest` function.

通用资源

¥Common assets

判断请求是否为常见资源请求包含以下条件:

¥The following conditions are included in determining whether a request is a common asset request:

  • 具有 file: 协议;

    ¥Has a file: protocol;

  • 具有常见静态资源提供程序的主机名(例如 fonts.googleapis.com);

    ¥Has a hostname of common static assets providers (e.g. fonts.googleapis.com);

  • 在其路径名中包含 /node_modules 子字符串;

    ¥Includes /node_modules substring in its pathname;

  • 在其路径名中包含 @vite

    ¥Includes @vite in its pathname;

  • 是 HTML (.html)、CSS (.css.scss.lass)、JavaScript (.js.jsx.mjs.ts.tsx.mts)、图片 (.jpg.jpeg.png.gif.avif.webp.svg)、字体 (.ttf.otf.woff.woff2.eot)、视频 (.mp4.webm.ogg.mov)、音频 (.mp3.ogg.flac.aac) 或其他文档格式 (.pdf.json.csv.zip.tar.gz.rar.7z) 请求。

    ¥Is an HTML (.html), CSS (.css, .scss, .lass), JavaScript (.js, .jsx, .mjs, .ts, .tsx, .mts), image (.jpg, .jpeg, .png, .gif, .avif, .webp, .svg), font (.ttf, .otf, .woff, .woff2, .eot), video (.mp4, .webm, .ogg, .mov), audio (.mp3, .ogg, .flac, .aac), or other document format (.pdf, .json, .csv, .zip, .tar, .gz, .rar, .7z) request.

用法

¥Usage

isCommonAssetRequest 函数旨在由 MSW 内部使用,以自动忽略常见的静态资源请求,避免其被视为未处理。你无需再手动检查。

¥The isCommonAssetRequest function is meant to be used internally by MSW to automatically ignore common static asset requests from being considered unhandled. You don’t have to check that manually anymore.

自定义 onUnhandledRequest 回调

¥Custom onUnhandledRequest callback

你可能需要使用此函数的一个用例是,在为 server/workeronUnhandledRequest 选项提供自定义函数时。这样做将退出默认静态资源排除,如果你想再次依赖它,则必须手动调用 isCommonAssetRequest

¥One use case where you may want to use this function is when providing a custom function to the onUnhandledRequest option of your server/worker. Doing so will opt out from the default static assets exclusion and you would have to call isCommonAssetRequest manually if you want to rely on it again.

import { isCommonAssetRequest } from 'msw'
const { setupWorker } from 'msw/browser'
 
const worker = setupWorker()
 
worker.start({
	onUnhandledRequest(request, print) {
		// List a custom request predicate.
		if (myCustomLogic(request)) {
			return
		}
 
		// Ignore common static asset requests
		// (i.e. tap into the default behavior).
		if (isCommonAssetRequest(request)) {
			return
		}
 
		// Otherwise, print a warning.
		print.warning()
	}
})