ReferenceError: Blob 未在 JavaScript 中定义 [已解决]

ReferenceError: Blob 未在 JavaScript 中定义

ReferenceError: Blob is not defined in JavaScript

Blob在未将类导入 Node.js 应用程序的情况下使用该类时,会发生“Blob 未定义”错误。

要解决该错误,请Blob在使用前导入该类,例如
import { Blob } from 'buffer';.

referenceerror blob 未定义

要解决该错误,请在使用前导入
Blob类。

索引.js
import {Blob} from 'buffer'; const blob = new Blob(['hello world']); console.log(blob); // 👉️ Blob { size: 11, type: '' }

该类Blob有两个参数:

  1. sources – 要存储在Blob
  2. options – an object, where we can set the endings to transparent or
    native (line endings get converted to the platform native line endings).
    The content-type of the Blob can also be set in the object.
The Blob constructor creates and returns a new Blob object that contains the concatenation of the provided sources.

You can modify the sources after the Blob is created.

Here’s an example where we explicitly set the content-type of the Blob.

index.js
import {Blob} from 'buffer'; const obj = {name: 'James Doe'}; const blob = new Blob([JSON.stringify(obj, null, 2)], { type: 'application/json', }); console.log(blob); // 👉️ Blob { size: 25, type: 'application/json' }

We constructed a Blob from a JSON string and set its content-type to
application/json.

Note that Blob is a globally available class in Node.js starting with version
18.

You can check your version of Node with the node -v command.

shell
node -v

如果您使用 Node.js 18+ 版本,您可以直接使用该类Blob而无需导入它。

索引.js
const blob = new Blob(['hello world']); console.log(blob); // 👉️ Blob { size: 11, type: '' }

使用cross-blob模块代替

使用内置类的另一种方法Blob是使用
cross-blob npm 模块。

该模块为 Node.js 和 Web 提供了跨平台的 blob 实现。

您可以cross-blob通过运行以下命令来安装。

# 👇️ with NPM npm install cross-blob # 👇️ with YARN yarn add cross-blob

现在您可以Blob按如下方式从包中导入类。

索引.js
import Blob from 'cross-blob'; const blob = new Blob(['hello world']); console.log(blob.size); // 👉️ 11 // Global patch (to support external modules like is-blob). globalThis.Blob = Blob;