UNPKG

19.3 kBMarkdownView Raw
1[npm]: https://img.shields.io/npm/v/@rollup/plugin-commonjs
2[npm-url]: https://www.npmjs.com/package/@rollup/plugin-commonjs
3[size]: https://packagephobia.now.sh/badge?p=@rollup/plugin-commonjs
4[size-url]: https://packagephobia.now.sh/result?p=@rollup/plugin-commonjs
5
6[![npm][npm]][npm-url]
7[![size][size]][size-url]
8[![libera manifesto](https://img.shields.io/badge/libera-manifesto-lightgrey.svg)](https://liberamanifesto.com)
9
10# @rollup/plugin-commonjs
11
12🍣 A Rollup plugin to convert CommonJS modules to ES6, so they can be included in a Rollup bundle
13
14## Requirements
15
16This plugin requires an [LTS](https://github.com/nodejs/Release) Node version (v14.0.0+) and Rollup v2.68.0+. If you are using [`@rollup/plugin-node-resolve`](https://github.com/rollup/plugins/tree/master/packages/node-resolve), it should be v13.0.6+.
17
18## Install
19
20Using npm:
21
22```bash
23npm install @rollup/plugin-commonjs --save-dev
24```
25
26## Usage
27
28Create a `rollup.config.js` [configuration file](https://www.rollupjs.org/guide/en/#configuration-files) and import the plugin:
29
30```js
31import commonjs from '@rollup/plugin-commonjs';
32
33export default {
34 input: 'src/index.js',
35 output: {
36 dir: 'output',
37 format: 'cjs'
38 },
39 plugins: [commonjs()]
40};
41```
42
43Then call `rollup` either via the [CLI](https://www.rollupjs.org/guide/en/#command-line-reference) or the [API](https://www.rollupjs.org/guide/en/#javascript-api).
44
45When used together with the node-resolve plugin
46
47## Options
48
49### `strictRequires`
50
51Type: `"auto" | boolean | "debug" | string[]`<br>
52Default: `"auto"`
53
54By default, this plugin will try to hoist `require` statements as imports to the top of each file. While this works well for many code bases and allows for very efficient ESM output, it does not perfectly capture CommonJS semantics as the initialisation order of required modules will be different. The resultant side effects can include log statements being emitted in a different order, and some code that is dependent on the initialisation order of polyfills in require statements may not work. But it is especially problematic when there are circular `require` calls between CommonJS modules as those often rely on the lazy execution of nested `require` calls.
55
56Setting this option to `true` will wrap all CommonJS files in functions which are executed when they are required for the first time, preserving NodeJS semantics. This is the safest setting and should be used if the generated code does not work correctly with `"auto"`. Note that `strictRequires: true` can have a small impact on the size and performance of generated code, but less so if the code is minified.
57
58The default value of `"auto"` will only wrap CommonJS files when they are part of a CommonJS dependency cycle, e.g. an index file that is required by some of its dependencies, or if they are only required in a potentially "conditional" way like from within an if-statement or a function. All other CommonJS files are hoisted. This is the recommended setting for most code bases. Note that the detection of conditional requires can be subject to race conditions if there are both conditional and unconditional requires of the same file, which in edge cases may result in inconsistencies between builds. If you think this is a problem for you, you can avoid this by using any value other than `"auto"` or `"debug"`.
59
60`false` will entirely prevent wrapping and hoist all files. This may still work depending on the nature of cyclic dependencies but will often cause problems.
61
62You can also provide a [picomatch pattern](https://github.com/micromatch/picomatch), or array of patterns, to only specify a subset of files which should be wrapped in functions for proper `require` semantics.
63
64`"debug"` works like `"auto"` but after bundling, it will display a warning containing a list of ids that have been wrapped which can be used as picomatch pattern for fine-tuning or to avoid the potential race conditions mentioned for `"auto"`.
65
66### `dynamicRequireTargets`
67
68Type: `string | string[]`<br>
69Default: `[]`
70
71_Note: In previous versions, this option would spin up a rather comprehensive mock environment that was capable of handling modules that manipulate `require.cache`. This is no longer supported. If you rely on this e.g. when using request-promise-native, use version 21 of this plugin._
72
73Some modules contain dynamic `require` calls, or require modules that contain circular dependencies, which are not handled well by static imports.
74Including those modules as `dynamicRequireTargets` will simulate a CommonJS (NodeJS-like) environment for them with support for dynamic dependencies. It also enables `strictRequires` for those modules, see above.
75
76_Note: In extreme cases, this feature may result in some paths being rendered as absolute in the final bundle. The plugin tries to avoid exposing paths from the local machine, but if you are `dynamicRequirePaths` with paths that are far away from your project's folder, that may require replacing strings like `"/Users/John/Desktop/foo-project/"` -> `"/"`._
77
78Example:
79
80```js
81commonjs({
82 dynamicRequireTargets: [
83 // include using a glob pattern (either a string or an array of strings)
84 'node_modules/logform/*.js',
85
86 // exclude files that are known to not be required dynamically, this allows for better optimizations
87 '!node_modules/logform/index.js',
88 '!node_modules/logform/format.js',
89 '!node_modules/logform/levels.js',
90 '!node_modules/logform/browser.js'
91 ]
92});
93```
94
95### `dynamicRequireRoot`
96
97Type: `string`<br>
98Default: `process.cwd()`
99
100To avoid long paths when using the `dynamicRequireTargets` option, you can use this option to specify a directory that is a common parent for all files that use dynamic require statements. Using a directory higher up such as `/` may lead to unnecessarily long paths in the generated code and may expose directory names on your machine like your home directory name. By default it uses the current working directory.
101
102### `exclude`
103
104Type: `string | string[]`<br>
105Default: `null`
106
107A [picomatch pattern](https://github.com/micromatch/picomatch), or array of patterns, which specifies the files in the build the plugin should _ignore_. By default, all files with extensions other than those in `extensions` or `".cjs"` are ignored, but you can exclude additional files. See also the `include` option.
108
109### `include`
110
111Type: `string | string[]`<br>
112Default: `null`
113
114A [picomatch pattern](https://github.com/micromatch/picomatch), or array of patterns, which specifies the files in the build the plugin should operate on. By default, all files with extension `".cjs"` or those in `extensions` are included, but you can narrow this list by only including specific files. These files will be analyzed and transpiled if either the analysis does not find ES module specific statements or `transformMixedEsModules` is `true`.
115
116### `extensions`
117
118Type: `string[]`<br>
119Default: `['.js']`
120
121For extensionless imports, search for extensions other than .js in the order specified. Note that you need to make sure that non-JavaScript files are transpiled by another plugin first.
122
123### `ignoreGlobal`
124
125Type: `boolean`<br>
126Default: `false`
127
128If true, uses of `global` won't be dealt with by this plugin.
129
130### `sourceMap`
131
132Type: `boolean`<br>
133Default: `true`
134
135If false, skips source map generation for CommonJS modules. This will improve performance.
136
137### `transformMixedEsModules`
138
139Type: `boolean`<br>
140Default: `false`
141
142Instructs the plugin whether to enable mixed module transformations. This is useful in scenarios with modules that contain a mix of ES `import` statements and CommonJS `require` expressions. Set to `true` if `require` calls should be transformed to imports in mixed modules, or `false` if the `require` expressions should survive the transformation. The latter can be important if the code contains environment detection, or you are coding for an environment with special treatment for `require` calls such as [ElectronJS](https://www.electronjs.org/). See also the "ignore" option.
143
144### `ignore`
145
146Type: `string[] | ((id: string) => boolean)`<br>
147Default: `[]`
148
149Sometimes you have to leave require statements unconverted. Pass an array containing the IDs or an `id => boolean` function.
150
151### `ignoreTryCatch`
152
153Type: `boolean | 'remove' | string[] | ((id: string) => boolean)`<br>
154Default: `true`
155
156In most cases, where `require` calls to external dependencies are inside a `try-catch` clause, they should be left unconverted as it requires an optional dependency that may or may not be installed beside the rolled up package.
157Due to the conversion of `require` to a static `import` - the call is hoisted to the top of the file, outside of the `try-catch` clause.
158
159- `true`: All external `require` calls inside a `try` will be left unconverted.
160- `false`: All external `require` calls inside a `try` will be converted as if the `try-catch` clause is not there.
161- `remove`: Remove all external `require` calls from inside any `try` block.
162- `string[]`: Pass an array containing the IDs to left unconverted.
163- `((id: string) => boolean|'remove')`: Pass a function that control individual IDs.
164
165Note that non-external requires will not be ignored by this option.
166
167### `ignoreDynamicRequires`
168
169Type: `boolean`
170Default: false
171
172Some `require` calls cannot be resolved statically to be translated to imports, e.g.
173
174```js
175function wrappedRequire(target) {
176 return require(target);
177}
178wrappedRequire('foo');
179wrappedRequire('bar');
180```
181
182When this option is set to `false`, the generated code will either directly throw an error when such a call is encountered or, when `dynamicRequireTargets` is used, when such a call cannot be resolved with a configured dynamic require target.
183
184Setting this option to `true` will instead leave the `require` call in the code or use it as a fallback for `dynamicRequireTargets`.
185
186### `esmExternals`
187
188Type: `boolean | string[] | ((id: string) => boolean)`
189Default: `false`
190
191Controls how to render imports from external dependencies. By default, this plugin assumes that all external dependencies are CommonJS. This means they are rendered as default imports to be compatible with e.g. NodeJS where ES modules can only import a default export from a CommonJS dependency:
192
193```js
194// input
195const foo = require('foo');
196
197// output
198import foo from 'foo';
199```
200
201This is likely not desired for ES module dependencies: Here `require` should usually return the namespace to be compatible with how bundled modules are handled.
202
203If you set `esmExternals` to `true`, this plugins assumes that all external dependencies are ES modules and will adhere to the `requireReturnsDefault` option. If that option is not set, they will be rendered as namespace imports.
204
205You can also supply an array of ids to be treated as ES modules, or a function that will be passed each external id to determine if it is an ES module.
206
207### `defaultIsModuleExports`
208
209Type: `boolean | "auto"`<br>
210Default: `"auto"`
211
212Controls what is the default export when importing a CommonJS file from an ES module.
213
214- `true`: The value of the default export is `module.exports`. This currently matches the behavior of Node.js when importing a CommonJS file.
215 ```js
216 // mod.cjs
217 exports.default = 3;
218 ```
219 ```js
220 import foo from './mod.cjs';
221 console.log(foo); // { default: 3 }
222 ```
223- `false`: The value of the default export is `exports.default`.
224 ```js
225 // mod.cjs
226 exports.default = 3;
227 ```
228 ```js
229 import foo from './mod.cjs';
230 console.log(foo); // 3
231 ```
232- `"auto"`: The value of the default export is `exports.default` if the CommonJS file has an `exports.__esModule === true` property; otherwise it's `module.exports`. This makes it possible to import
233 the default export of ES modules compiled to CommonJS as if they were not compiled.
234 ```js
235 // mod.cjs
236 exports.default = 3;
237 ```
238 ```js
239 // mod-compiled.cjs
240 exports.__esModule = true;
241 exports.default = 3;
242 ```
243 ```js
244 import foo from './mod.cjs';
245 import bar from './mod-compiled.cjs';
246 console.log(foo); // { default: 3 }
247 console.log(bar); // 3
248 ```
249
250### `requireReturnsDefault`
251
252Type: `boolean | "namespace" | "auto" | "preferred" | ((id: string) => boolean | "auto" | "preferred")`<br>
253Default: `false`
254
255Controls what is returned when requiring an ES module from a CommonJS file. When using the `esmExternals` option, this will also apply to external modules. By default, this plugin will render those imports as namespace imports, i.e.
256
257```js
258// input
259const foo = require('foo');
260
261// output
262import * as foo from 'foo';
263```
264
265This is in line with how other bundlers handle this situation and is also the most likely behaviour in case Node should ever support this. However there are some situations where this may not be desired:
266
267- There is code in an external dependency that cannot be changed where a `require` statement expects the default export to be returned from an ES module.
268- If the imported module is in the same bundle, Rollup will generate a namespace object for the imported module which can increase bundle size unnecessarily:
269
270 ```js
271 // input: main.js
272 const dep = require('./dep.js');
273 console.log(dep.default);
274
275 // input: dep.js
276 export default 'foo';
277
278 // output
279 var dep = 'foo';
280
281 var dep$1 = /*#__PURE__*/ Object.freeze({
282 __proto__: null,
283 default: dep
284 });
285
286 console.log(dep$1.default);
287 ```
288
289For these situations, you can change Rollup's behaviour either globally or per module. To change it globally, set the `requireReturnsDefault` option to one of the following values:
290
291- `false`: This is the default, requiring an ES module returns its namespace. This is the only option that will also add a marker `__esModule: true` to the namespace to support interop patterns in CommonJS modules that are transpiled ES modules.
292
293 ```js
294 // input
295 const dep = require('dep');
296 console.log(dep);
297
298 // output
299 import * as dep$1 from 'dep';
300
301 function getAugmentedNamespace(n) {
302 var a = Object.defineProperty({}, '__esModule', { value: true });
303 Object.keys(n).forEach(function (k) {
304 var d = Object.getOwnPropertyDescriptor(n, k);
305 Object.defineProperty(
306 a,
307 k,
308 d.get
309 ? d
310 : {
311 enumerable: true,
312 get: function () {
313 return n[k];
314 }
315 }
316 );
317 });
318 return a;
319 }
320
321 var dep = /*@__PURE__*/ getAugmentedNamespace(dep$1);
322
323 console.log(dep);
324 ```
325
326- `"namespace"`: Like `false`, requiring an ES module returns its namespace, but the plugin does not add the `__esModule` marker and thus creates more efficient code. For external dependencies when using `esmExternals: true`, no additional interop code is generated.
327
328 ```js
329 // output
330 import * as dep from 'dep';
331
332 console.log(dep);
333 ```
334
335- `"auto"`: This is complementary to how [`output.exports`](https://rollupjs.org/guide/en/#outputexports): `"auto"` works in Rollup: If a module has a default export and no named exports, requiring that module returns the default export. In all other cases, the namespace is returned. For external dependencies when using `esmExternals: true`, a corresponding interop helper is added:
336
337 ```js
338 // output
339 import * as dep$1 from 'dep';
340
341 function getDefaultExportFromNamespaceIfNotNamed(n) {
342 return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1
343 ? n['default']
344 : n;
345 }
346
347 var dep = getDefaultExportFromNamespaceIfNotNamed(dep$1);
348
349 console.log(dep);
350 ```
351
352- `"preferred"`: If a module has a default export, requiring that module always returns the default export, no matter whether additional named exports exist. This is similar to how previous versions of this plugin worked. Again for external dependencies when using `esmExternals: true`, an interop helper is added:
353
354 ```js
355 // output
356 import * as dep$1 from 'dep';
357
358 function getDefaultExportFromNamespaceIfPresent(n) {
359 return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
360 }
361
362 var dep = getDefaultExportFromNamespaceIfPresent(dep$1);
363
364 console.log(dep);
365 ```
366
367- `true`: This will always try to return the default export on require without checking if it actually exists. This can throw at build time if there is no default export. This is how external dependencies are handled when `esmExternals` is not used. The advantage over the other options is that, like `false`, this does not add an interop helper for external dependencies, keeping the code lean:
368
369 ```js
370 // output
371 import dep from 'dep';
372
373 console.log(dep);
374 ```
375
376To change this for individual modules, you can supply a function for `requireReturnsDefault` instead. This function will then be called once for each required ES module or external dependency with the corresponding id and allows you to return different values for different modules.
377
378## Using with @rollup/plugin-node-resolve
379
380Since most CommonJS packages you are importing are probably dependencies in `node_modules`, you may need to use [@rollup/plugin-node-resolve](https://github.com/rollup/plugins/tree/master/packages/node-resolve):
381
382```js
383// rollup.config.js
384import resolve from '@rollup/plugin-node-resolve';
385import commonjs from '@rollup/plugin-commonjs';
386
387export default {
388 input: 'main.js',
389 output: {
390 file: 'bundle.js',
391 format: 'iife',
392 name: 'MyModule'
393 },
394 plugins: [commonjs(), resolve()]
395};
396```
397
398## Usage with symlinks
399
400Symlinks are common in monorepos and are also created by the `npm link` command. Rollup with `@rollup/plugin-node-resolve` resolves modules to their real paths by default. So `include` and `exclude` paths should handle real paths rather than symlinked paths (e.g. `../common/node_modules/**` instead of `node_modules/**`). You may also use a regular expression for `include` that works regardless of base path. Try this:
401
402```js
403commonjs({
404 include: /node_modules/
405});
406```
407
408Whether symlinked module paths are [realpathed](http://man7.org/linux/man-pages/man3/realpath.3.html) or preserved depends on Rollup's `preserveSymlinks` setting, which is false by default, matching Node.js' default behavior. Setting `preserveSymlinks` to true in your Rollup config will cause `import` and `export` to match based on symlinked paths instead.
409
410## Strict mode
411
412ES modules are _always_ parsed in strict mode. That means that certain non-strict constructs (like octal literals) will be treated as syntax errors when Rollup parses modules that use them. Some older CommonJS modules depend on those constructs, and if you depend on them your bundle will blow up. There's basically nothing we can do about that.
413
414Luckily, there is absolutely no good reason _not_ to use strict mode for everything — so the solution to this problem is to lobby the authors of those modules to update them.
415
416## Inter-plugin-communication
417
418This plugin exposes the result of its CommonJS file type detection for other plugins to use. You can access it via `this.getModuleInfo` or the `moduleParsed` hook:
419
420```js
421function cjsDetectionPlugin() {
422 return {
423 name: 'cjs-detection',
424 moduleParsed({
425 id,
426 meta: {
427 commonjs: { isCommonJS }
428 }
429 }) {
430 console.log(`File ${id} is CommonJS: ${isCommonJS}`);
431 }
432 };
433}
434```
435
436## Meta
437
438[CONTRIBUTING](/.github/CONTRIBUTING.md)
439
440[LICENSE (MIT)](/LICENSE)