# @rollup/pluginutils 中文文档

规范地址：https://npmcn.com/package/%40rollup/pluginutils/

版本：5\.5\.1
npm 元数据更新时间：2026-10-21T19:34:29.375Z
中文译文更新时间：2026-11-05T15:48:28.918Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40rollup/pluginutils
原文对照：https://npmcn.com/package/%40rollup/pluginutils/?lang=original
项目主页：https://github.com/rollup/plugins/tree/master/packages/pluginutils#readme
源码仓库：https://github.com/rollup/plugins

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：68.6 kB，8 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=14\.0\.0
- 运行依赖：3 个
- peer 依赖：rollup ^1\.20\.0\|\|^2\.0\.0\|\|^3\.0\.0\|\|^4\.0\.0
- 首次发布：2019-11-25T19:15:21.415Z
- 最新版本发布：2026-10-21T19:34:28.985Z
- 近 30 天下载量：319010169（2026-10-07 至 2026-11-05，npm 官方下载统计）
- 已发布版本数：33（近 12 个月 3 个）

## 中文简介

Rollup 插件常用的一套功能

## 安装

```sh
npm install @rollup/pluginutils
```

也可以使用：`pnpm add @rollup/pluginutils`、`yarn add @rollup/pluginutils`、`bun add @rollup/pluginutils`

## README

[![npm](https://img.shields.io/npm/v/@rollup/pluginutils)](https://www.npmjs.com/package/@rollup/pluginutils) [![size](https://packagephobia.now.sh/badge?p=@rollup/pluginutils)](https://packagephobia.now.sh/result?p=@rollup/pluginutils) [![libera manifesto](https://img.shields.io/badge/libera-manifesto-lightgrey.svg)](https://liberamanifesto.com/)

# @ rollup/ pluginutils

由QQ Rollup插件常用的一套公用功能.

## 所需资源

插件 utils 需要一个 [长期](https://github.com/nodejs/Release) 节点版本(v14.0.0+)和"滚动"v1.2.0.0+.

## 安装

使用 npm :

```console
npm install @rollup/pluginutils --save-dev
```

## 使用量

```js
import utils from '@rollup/pluginutils';
//...
```

## API 密码

现有公用事业职能如下:

_注:参数名称紧接其后 `?` 表示参数是可选的._

### 扩展

如果模块 ID 不存在,则在模块 ID 中添加扩展名.

参数: `(filename: String, ext?: String)`  
回返情况: `String`

```js
import { addExtension } from '@rollup/pluginutils';

export default function myPlugin(options = {}) {
  return {
    resolveId(code, id) {
      // only adds an extension if there isn't one already
      id = addExtension(id); // `foo` -> `foo.js`, `foo.js` -> `foo.js`
      id = addExtension(id, '.myext'); // `foo` -> `foo.myext`, `foo.js` -> `foo.js`
    }
  };
}
```

### 附 录

附 录 `Scope` 对象到 AST 的相关节点。 每个 `Scope` 对象有一个 `scope.contains(name)` 返回的方法 `true` 如果在当前范围或母范围中定义了某个名称.

参数: `(ast: Node, propertyName?: String)`  
回返情况: `Object`

见 [@ rollup/ plugin- 注射](https://github.com/rollup/plugins/tree/master/packages/inject) 或者说 [@ rollup/ plugin- commonjs (英语)](https://github.com/rollup/plugins/tree/master/packages/commonjs) 作为使用的例子.

```js
import { attachScopes } from '@rollup/pluginutils';
import { walk } from 'estree-walker';

export default function myPlugin(options = {}) {
  return {
    transform(code) {
      const ast = this.parse(code);

      let scope = attachScopes(ast, 'scope');

      walk(ast, {
        enter(node) {
          if (node.scope) scope = node.scope;

          if (!scope.contains('foo')) {
            // `foo` is not defined, so if we encounter it,
            // we assume it's a global
          }
        },
        leave(node) {
          if (node.scope) scope = scope.parent;
        }
      });
    }
  };
}
```

### 创建筛选

构造一个过滤函数,用于确定是否应该运行某些模块.

参数: `(include?: <picomatch>, exclude?: <picomatch>, options?: Object)`  
回返情况: `(id: string | unknown) => boolean`

#### `include` 财务报告和审定财务报表 `exclude`

类型 : `String | RegExp | Array[...String|RegExp]`  

一个有效的 [`picomatch`](https://github.com/micromatch/picomatch#globbing-features) 模式,或一系列模式。 若为 `options.include` 被省略或有零长度,过滤器将返回 `true` 默认。 否则,身份证必须匹配其中一个或多个 `picomatch` 模式,并且不得与 `options.exclude` 模式.

请注意: `picomatch` 模式与 [`minimatch`](https://github.com/isaacs/minimatch#readme) 在多数情况下,它们可以互换。 如果您有更具体的模式匹配需求, 您可以查看 [本比较表](https://github.com/micromatch/picomatch#library-comparisons) 了解图书馆的不同之处.

#### `options`

##### `resolve`

类型 : `String | Boolean | null`

可选解决模式相对于目录以外的 `process.cwd()`如为 `String` ,然后该值将用作基准目录。 相对路径将针对 `process.cwd()` 先说 若为 `false`,那么这些模式将不会以任何目录来解决。 如果您想要为虚拟模块名称创建过滤器,此选项可能有用 .

#### 使用量

```js
import { createFilter } from '@rollup/pluginutils';

export default function myPlugin(options = {}) {
  // assume that the myPlugin accepts options of `options.include` and `options.exclude`
  var filter = createFilter(options.include, options.exclude, {
    resolve: '/my/base/dir'
  });

  return {
    transform(code, id) {
      if (!filter(id)) return;

      // proceed with the transformation...
    }
  };
}
```

### 数据toEsm

将对象转换为可树摇动的ES模块导入.

参数: `(data: Object, options: DataToEsmOptions)`  
回返情况: `String`

#### `data`

类型 : `Object`

一个可以转换成ES模块的对象.

#### `options`

类型 : `DataToEsmOptions`

_注意: 这些选项的完整文档请参见TypeScript定义_

#### 使用量

```js
import { dataToEsm } from '@rollup/pluginutils';

const esModuleSource = dataToEsm(
  {
    custom: 'data',
    to: ['treeshake']
  },
  {
    compact: false,
    indent: '\t',
    preferConst: true,
    objectShorthand: true,
    namedExports: true,
    includeArbitraryNames: false
  }
);
/*
Outputs the string ES module source:
  export const custom = 'data';
  export const to = ['treeshake'];
  export default { custom, to };
*/
```

### 已签名的名称

根据指定的模式提取所有任务目标的名称.

参数: `(param: Node)`  
回返情况: `Array[...String]`

#### `param`

类型 : `Node`

一个 `acorn` AST节点.

#### 使用量

```js
import { extractAssignedNames } from '@rollup/pluginutils';
import { walk } from 'estree-walker';

export default function myPlugin(options = {}) {
  return {
    transform(code) {
      const ast = this.parse(code);

      walk(ast, {
        enter(node) {
          if (node.type === 'VariableDeclarator') {
            const declaredNames = extractAssignedNames(node.id);
            // do something with the declared names
            // e.g. for `const {x, y: z} = ...` => declaredNames = ['x', 'z']
          }
        }
      });
    }
  };
}
```

### 准确的Regex

构造一个匹配指定字符串的 RegExp。 这对插件钩过滤器有用 .

参数: `(str: String | Array[...String], flags?: String)`  
回返情况: `RegExp`

#### 使用量

```js
import { exactRegex } from '@rollup/pluginutils';

exactRegex('foobar'); // /^foobar$/
exactRegex(['foo', 'bar']); // /^(?:foo|bar)$/
exactRegex('foo(bar)', 'i'); // /^foo\(bar\)$/i
```

### 创建法律标识符

构造一个捆绑安全标识符 `String`。 。 。 .

参数: `(str: String)`  
回返情况: `String`

#### 使用量

```js
import { makeLegalIdentifier } from '@rollup/pluginutils';

makeLegalIdentifier('foo-bar'); // 'foo_bar'
makeLegalIdentifier('typeof'); // '_typeof'
```

### 常态Path

将路径分隔符转换为前切.

参数: `(filename: String)`  
回返情况: `String`

#### 使用量

```js
import { normalizePath } from '@rollup/pluginutils';

normalizePath('foo\\bar'); // 'foo/bar'
normalizePath('foo/bar'); // 'foo/bar'
```

### 前缀Regex

构造匹配有指定前缀的值的 RegExp。 这对插件钩过滤器有用 .

参数: `(str: String | Array[...String], flags?: String)`  
回返情况: `RegExp`

#### 使用量

```js
import { prefixRegex } from '@rollup/pluginutils';

prefixRegex('foobar'); // /^foobar/
prefixRegex(['foo', 'bar']); // /^(?:foo|bar)/
prefixRegex('foo(bar)', 'i'); // /^foo\(bar\)/i
```

### 后缀

构造一个匹配带有指定后缀的值的RegExp。 这对插件钩过滤器有用 .

参数: `(str: String | Array[...String], flags?: String)`  
回返情况: `RegExp`

#### 使用量

```js
import { suffixRegex } from '@rollup/pluginutils';

suffixRegex('foobar'); // /foobar$/
suffixRegex(['foo', 'bar']); // /(?:foo|bar)$/
suffixRegex('foo(bar)', 'i'); // /foo\(bar\)$/i
```

## 元数据

[捐款](https://npmcn.com/.github/CONTRIBUTING.md)

[利比里亚(麻省理工学院)](https://npmcn.com/LICENSE)

## 常见问题

### @rollup/pluginutils 是什么？

Rollup 插件常用的一套功能

### 如何安装 @rollup/pluginutils？

在项目目录运行 npm install @rollup/pluginutils，或使用 pnpm add / yarn add / bun add。

### @rollup/pluginutils 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @rollup/pluginutils 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @rollup/pluginutils 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=14\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @rollup/pluginutils 可以商用吗？

@rollup/pluginutils 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @rollup/pluginutils 的下载量有多少？

根据 npm 官方下载统计，@rollup/pluginutils 在 2026/10/07 – 2026/11/05 这 30 天内被下载 319,010,169 次，日均约 10,633,672 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @rollup/pluginutils 还在维护吗？

最新版本 5\.5\.1 发布于 2026/10/22（17 天前）；至今共发布 33 个版本，其中过去 12 个月发布了 3 个；首次发布于 2019/11/26。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

