@rollup/pluginutils

中文文档
5.5.1发布于 2026/10/22MITTypeScriptESM + CJS构建来源已验证近 30 天下载 3.2亿

A set of utility functions commonly used by Rollup plugins

原始使用文档
文档目录15 节
  1. Requirements
  2. Install
  3. Usage
  4. API
  5. addExtension
  6. attachScopes
  7. createFilter
  8. dataToEsm
  9. extractAssignedNames
  10. exactRegex
  11. makeLegalIdentifier
  12. normalizePath
  13. prefixRegex
  14. suffixRegex
  15. Meta

npm size libera manifesto

@rollup/pluginutils

A set of utility functions commonly used by 🍣 Rollup plugins.

Requirements

The plugin utils require an LTS Node version (v14.0.0+) and Rollup v1.20.0+.

Install

Using npm:

npm install @rollup/pluginutils --save-dev

Usage

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

API

Available utility functions are listed below:

Note: Parameter names immediately followed by a ? indicate that the parameter is optional.

addExtension

Adds an extension to a module ID if one does not exist.

Parameters: (filename: String, ext?: String)
Returns: String

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`
    }
  };
}

attachScopes

Attaches Scope objects to the relevant nodes of an AST. Each Scope object has a scope.contains(name) method that returns true if a given name is defined in the current scope or a parent scope.

Parameters: (ast: Node, propertyName?: String)
Returns: Object

See @rollup/plugin-inject or @rollup/plugin-commonjs for an example of usage.

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;
        }
      });
    }
  };
}

createFilter

Constructs a filter function which can be used to determine whether or not certain modules should be operated upon.

Parameters: (include?: <picomatch>, exclude?: <picomatch>, options?: Object)
Returns: (id: string | unknown) => boolean

include and exclude

Type: String | RegExp | Array[...String|RegExp]

A valid picomatch pattern, or array of patterns. If options.include is omitted or has zero length, filter will return true by default. Otherwise, an ID must match one or more of the picomatch patterns, and must not match any of the options.exclude patterns.

Note that picomatch patterns are very similar to minimatch patterns, and in most use cases, they are interchangeable. If you have more specific pattern matching needs, you can view this comparison table to learn more about where the libraries differ.

options

resolve

Type: String | Boolean | null

Optionally resolves the patterns against a directory other than process.cwd(). If a String is specified, then the value will be used as the base directory. Relative paths will be resolved against process.cwd() first. If false, then the patterns will not be resolved against any directory. This can be useful if you want to create a filter for virtual module names.

Usage

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...
    }
  };
}

dataToEsm

Transforms objects into tree-shakable ES Module imports.

Parameters: (data: Object, options: DataToEsmOptions)
Returns: String

data

Type: Object

An object to transform into an ES module.

options

Type: DataToEsmOptions

Note: Please see the TypeScript definition for complete documentation of these options

Usage

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 };
*/

extractAssignedNames

Extracts the names of all assignment targets based upon specified patterns.

Parameters: (param: Node)
Returns: Array[...String]

param

Type: Node

An acorn AST Node.

Usage

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']
          }
        }
      });
    }
  };
}

exactRegex

Constructs a RegExp that matches the exact string specified. This is useful for plugin hook filters.

Parameters: (str: String | Array[...String], flags?: String)
Returns: RegExp

Usage

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

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

makeLegalIdentifier

Constructs a bundle-safe identifier from a String.

Parameters: (str: String)
Returns: String

Usage

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

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

normalizePath

Converts path separators to forward slash.

Parameters: (filename: String)
Returns: String

Usage

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

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

prefixRegex

Constructs a RegExp that matches a value that has the specified prefix. This is useful for plugin hook filters.

Parameters: (str: String | Array[...String], flags?: String)
Returns: RegExp

Usage

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

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

suffixRegex

Constructs a RegExp that matches a value that has the specified suffix. This is useful for plugin hook filters.

Parameters: (str: String | Array[...String], flags?: String)
Returns: RegExp

Usage

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

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

Meta

CONTRIBUTING

LICENSE (MIT)

版本与发布记录

@rollup/pluginutils 共发布 33 个版本,首次发布于 2019/11/26;过去 12 个月发布了 3 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
5.5.1latest2026/10/2217 天前
5.5.02026/10/2217 天前
5.4.02026/05/295 个月前
5.3.02025/09/041.2 年前
5.2.02025/06/171.4 年前
5.1.42024/12/161.9 年前

关于 @rollup/pluginutils 的常见问题

@rollup/pluginutils 是什么?

A set of utility functions commonly used by Rollup plugins

如何安装 @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 和提交记录判断。