e78f4bdd6e6766cfa725b3143a9056a27c8b54a3caf735057e097ee24546cef36d88fbc60b518e6252b011da22280b5333a59521dd9a025f54193ebecb281c 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. [npm]: https://img.shields.io/npm/v/@rollup/pluginutils
  2. [npm-url]: https://www.npmjs.com/package/@rollup/pluginutils
  3. [size]: https://packagephobia.now.sh/badge?p=@rollup/pluginutils
  4. [size-url]: https://packagephobia.now.sh/result?p=@rollup/pluginutils
  5. [![npm][npm]][npm-url]
  6. [![size][size]][size-url]
  7. [![libera manifesto](https://img.shields.io/badge/libera-manifesto-lightgrey.svg)](https://liberamanifesto.com)
  8. # @rollup/pluginutils
  9. A set of utility functions commonly used by 🍣 Rollup plugins.
  10. ## Requirements
  11. The plugin utils require an [LTS](https://github.com/nodejs/Release) Node version (v14.0.0+) and Rollup v1.20.0+.
  12. ## Install
  13. Using npm:
  14. ```console
  15. npm install @rollup/pluginutils --save-dev
  16. ```
  17. ## Usage
  18. ```js
  19. import utils from '@rollup/pluginutils';
  20. //...
  21. ```
  22. ## API
  23. Available utility functions are listed below:
  24. _Note: Parameter names immediately followed by a `?` indicate that the parameter is optional._
  25. ### addExtension
  26. Adds an extension to a module ID if one does not exist.
  27. Parameters: `(filename: String, ext?: String)`<br>
  28. Returns: `String`
  29. ```js
  30. import { addExtension } from '@rollup/pluginutils';
  31. export default function myPlugin(options = {}) {
  32. return {
  33. resolveId(code, id) {
  34. // only adds an extension if there isn't one already
  35. id = addExtension(id); // `foo` -> `foo.js`, `foo.js` -> `foo.js`
  36. id = addExtension(id, '.myext'); // `foo` -> `foo.myext`, `foo.js` -> `foo.js`
  37. }
  38. };
  39. }
  40. ```
  41. ### attachScopes
  42. 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.
  43. Parameters: `(ast: Node, propertyName?: String)`<br>
  44. Returns: `Object`
  45. See [@rollup/plugin-inject](https://github.com/rollup/plugins/tree/master/packages/inject) or [@rollup/plugin-commonjs](https://github.com/rollup/plugins/tree/master/packages/commonjs) for an example of usage.
  46. ```js
  47. import { attachScopes } from '@rollup/pluginutils';
  48. import { walk } from 'estree-walker';
  49. export default function myPlugin(options = {}) {
  50. return {
  51. transform(code) {
  52. const ast = this.parse(code);
  53. let scope = attachScopes(ast, 'scope');
  54. walk(ast, {
  55. enter(node) {
  56. if (node.scope) scope = node.scope;
  57. if (!scope.contains('foo')) {
  58. // `foo` is not defined, so if we encounter it,
  59. // we assume it's a global
  60. }
  61. },
  62. leave(node) {
  63. if (node.scope) scope = scope.parent;
  64. }
  65. });
  66. }
  67. };
  68. }
  69. ```
  70. ### createFilter
  71. Constructs a filter function which can be used to determine whether or not certain modules should be operated upon.
  72. Parameters: `(include?: <picomatch>, exclude?: <picomatch>, options?: Object)`<br>
  73. Returns: `(id: string | unknown) => boolean`
  74. #### `include` and `exclude`
  75. Type: `String | RegExp | Array[...String|RegExp]`<br>
  76. A valid [`picomatch`](https://github.com/micromatch/picomatch#globbing-features) 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.
  77. Note that `picomatch` patterns are very similar to [`minimatch`](https://github.com/isaacs/minimatch#readme) patterns, and in most use cases, they are interchangeable. If you have more specific pattern matching needs, you can view [this comparison table](https://github.com/micromatch/picomatch#library-comparisons) to learn more about where the libraries differ.
  78. #### `options`
  79. ##### `resolve`
  80. Type: `String | Boolean | null`
  81. 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.
  82. #### Usage
  83. ```js
  84. import { createFilter } from '@rollup/pluginutils';
  85. export default function myPlugin(options = {}) {
  86. // assume that the myPlugin accepts options of `options.include` and `options.exclude`
  87. var filter = createFilter(options.include, options.exclude, {
  88. resolve: '/my/base/dir'
  89. });
  90. return {
  91. transform(code, id) {
  92. if (!filter(id)) return;
  93. // proceed with the transformation...
  94. }
  95. };
  96. }
  97. ```
  98. ### dataToEsm
  99. Transforms objects into tree-shakable ES Module imports.
  100. Parameters: `(data: Object, options: DataToEsmOptions)`<br>
  101. Returns: `String`
  102. #### `data`
  103. Type: `Object`
  104. An object to transform into an ES module.
  105. #### `options`
  106. Type: `DataToEsmOptions`
  107. _Note: Please see the TypeScript definition for complete documentation of these options_
  108. #### Usage
  109. ```js
  110. import { dataToEsm } from '@rollup/pluginutils';
  111. const esModuleSource = dataToEsm(
  112. {
  113. custom: 'data',
  114. to: ['treeshake']
  115. },
  116. {
  117. compact: false,
  118. indent: '\t',
  119. preferConst: true,
  120. objectShorthand: true,
  121. namedExports: true,
  122. includeArbitraryNames: false
  123. }
  124. );
  125. /*
  126. Outputs the string ES module source:
  127. export const custom = 'data';
  128. export const to = ['treeshake'];
  129. export default { custom, to };
  130. */
  131. ```
  132. ### extractAssignedNames
  133. Extracts the names of all assignment targets based upon specified patterns.
  134. Parameters: `(param: Node)`<br>
  135. Returns: `Array[...String]`
  136. #### `param`
  137. Type: `Node`
  138. An `acorn` AST Node.
  139. #### Usage
  140. ```js
  141. import { extractAssignedNames } from '@rollup/pluginutils';
  142. import { walk } from 'estree-walker';
  143. export default function myPlugin(options = {}) {
  144. return {
  145. transform(code) {
  146. const ast = this.parse(code);
  147. walk(ast, {
  148. enter(node) {
  149. if (node.type === 'VariableDeclarator') {
  150. const declaredNames = extractAssignedNames(node.id);
  151. // do something with the declared names
  152. // e.g. for `const {x, y: z} = ...` => declaredNames = ['x', 'z']
  153. }
  154. }
  155. });
  156. }
  157. };
  158. }
  159. ```
  160. ### exactRegex
  161. Constructs a RegExp that matches the exact string specified. This is useful for plugin hook filters.
  162. Parameters: `(str: String | Array[...String], flags?: String)`<br>
  163. Returns: `RegExp`
  164. #### Usage
  165. ```js
  166. import { exactRegex } from '@rollup/pluginutils';
  167. exactRegex('foobar'); // /^foobar$/
  168. exactRegex(['foo', 'bar']); // /^(?:foo|bar)$/
  169. exactRegex('foo(bar)', 'i'); // /^foo\(bar\)$/i
  170. ```
  171. ### makeLegalIdentifier
  172. Constructs a bundle-safe identifier from a `String`.
  173. Parameters: `(str: String)`<br>
  174. Returns: `String`
  175. #### Usage
  176. ```js
  177. import { makeLegalIdentifier } from '@rollup/pluginutils';
  178. makeLegalIdentifier('foo-bar'); // 'foo_bar'
  179. makeLegalIdentifier('typeof'); // '_typeof'
  180. ```
  181. ### normalizePath
  182. Converts path separators to forward slash.
  183. Parameters: `(filename: String)`<br>
  184. Returns: `String`
  185. #### Usage
  186. ```js
  187. import { normalizePath } from '@rollup/pluginutils';
  188. normalizePath('foo\\bar'); // 'foo/bar'
  189. normalizePath('foo/bar'); // 'foo/bar'
  190. ```
  191. ### prefixRegex
  192. Constructs a RegExp that matches a value that has the specified prefix. This is useful for plugin hook filters.
  193. Parameters: `(str: String | Array[...String], flags?: String)`<br>
  194. Returns: `RegExp`
  195. #### Usage
  196. ```js
  197. import { prefixRegex } from '@rollup/pluginutils';
  198. prefixRegex('foobar'); // /^foobar/
  199. prefixRegex(['foo', 'bar']); // /^(?:foo|bar)/
  200. prefixRegex('foo(bar)', 'i'); // /^foo\(bar\)/i
  201. ```
  202. ### suffixRegex
  203. Constructs a RegExp that matches a value that has the specified suffix. This is useful for plugin hook filters.
  204. Parameters: `(str: String | Array[...String], flags?: String)`<br>
  205. Returns: `RegExp`
  206. #### Usage
  207. ```js
  208. import { suffixRegex } from '@rollup/pluginutils';
  209. suffixRegex('foobar'); // /foobar$/
  210. suffixRegex(['foo', 'bar']); // /(?:foo|bar)$/
  211. suffixRegex('foo(bar)', 'i'); // /foo\(bar\)$/i
  212. ```
  213. ## Meta
  214. [CONTRIBUTING](/.github/CONTRIBUTING.md)
  215. [LICENSE (MIT)](/LICENSE)