UNPKG

15.7 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 (v8.0.0+) and Rollup v1.20.0+.
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
45## Options
46
47### `dynamicRequireTargets`
48
49Type: `string | string[]`<br>
50Default: `[]`
51
52Some modules contain dynamic `require` calls, or require modules that contain circular dependencies, which are not handled well by static imports.
53Including those modules as `dynamicRequireTargets` will simulate a CommonJS (NodeJS-like) environment for them with support for dynamic and circular dependencies.
54
55_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/"` -> `"/"`._
56
57Example:
58
59```js
60commonjs({
61 dynamicRequireTargets: [
62 // include using a glob pattern (either a string or an array of strings)
63 'node_modules/logform/*.js',
64
65 // exclude files that are known to not be required dynamically, this allows for better optimizations
66 '!node_modules/logform/index.js',
67 '!node_modules/logform/format.js',
68 '!node_modules/logform/levels.js',
69 '!node_modules/logform/browser.js'
70 ]
71});
72```
73
74### `exclude`
75
76Type: `string | string[]`<br>
77Default: `null`
78
79A [minimatch pattern](https://github.com/isaacs/minimatch), 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.
80
81### `include`
82
83Type: `string | string[]`<br>
84Default: `null`
85
86A [minimatch pattern](https://github.com/isaacs/minimatch), 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`.
87
88### `extensions`
89
90Type: `string[]`<br>
91Default: `['.js']`
92
93For 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.
94
95### `ignoreGlobal`
96
97Type: `boolean`<br>
98Default: `false`
99
100If true, uses of `global` won't be dealt with by this plugin.
101
102### `sourceMap`
103
104Type: `boolean`<br>
105Default: `true`
106
107If false, skips source map generation for CommonJS modules. This will improve performance.
108
109### `transformMixedEsModules`
110
111Type: `boolean`<br>
112Default: `false`
113
114Instructs 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.
115
116### `ignore`
117
118Type: `string[] | ((id: string) => boolean)`<br>
119Default: `[]`
120
121Sometimes you have to leave require statements unconverted. Pass an array containing the IDs or an `id => boolean` function.
122
123### `ignoreTryCatch`
124
125Type: `boolean | 'remove' | string[] | ((id: string) => boolean)`<br>
126Default: `true`
127
128In most cases, where `require` calls 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.
129Due 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.
130
131- `true`: All `require` calls inside a `try` will be left unconverted.
132- `false`: All `require` calls inside a `try` will be converted as if the `try-catch` clause is not there.
133- `remove`: Remove all `require` calls from inside any `try` block.
134- `string[]`: Pass an array containing the IDs to left unconverted.
135- `((id: string) => boolean|'remove')`: Pass a function that control individual IDs.
136
137### `ignoreDynamicRequires`
138
139Type: `boolean`
140Default: false
141
142Some `require` calls cannot be resolved statically to be translated to imports, e.g.
143
144```js
145function wrappedRequire(target) {
146 return require(target);
147}
148wrappedRequire('foo');
149wrappedRequire('bar');
150```
151
152When 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.
153
154Setting this option to `true` will instead leave the `require` call in the code or use it as a fallback for `dynamicRequireTargets`.
155
156### `esmExternals`
157
158Type: `boolean | string[] | ((id: string) => boolean)`
159Default: `false`
160
161Controls 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:
162
163```js
164// input
165const foo = require('foo');
166
167// output
168import foo from 'foo';
169```
170
171This is likely not desired for ES module dependencies: Here `require` should usually return the namespace to be compatible with how bundled modules are handled.
172
173If 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.
174
175You 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.
176
177### `defaultIsModuleExports`
178
179Type: `boolean | "auto"`<br>
180Default: `"auto"`
181
182Controls what is the default export when importing a CommonJS file from an ES module.
183
184- `true`: The value of the default export is `module.exports`. This currently matches the behavior of Node.js when importing a CommonJS file.
185 ```js
186 // mod.cjs
187 exports.default = 3;
188 ```
189 ```js
190 import foo from './mod.cjs';
191 console.log(foo); // { default: 3 }
192 ```
193- `false`: The value of the default export is `exports.default`.
194 ```js
195 // mod.cjs
196 exports.default = 3;
197 ```
198 ```js
199 import foo from './mod.cjs';
200 console.log(foo); // 3
201 ```
202- `"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
203 the default export of ES modules compiled to CommonJS as if they were not compiled.
204 ```js
205 // mod.cjs
206 exports.default = 3;
207 ```
208 ```js
209 // mod-compiled.cjs
210 exports.__esModule = true;
211 exports.default = 3;
212 ```
213 ```js
214 import foo from './mod.cjs';
215 import bar from './mod-compiled.cjs';
216 console.log(foo); // { default: 3 }
217 console.log(bar); // 3
218 ```
219
220### `requireReturnsDefault`
221
222Type: `boolean | "namespace" | "auto" | "preferred" | ((id: string) => boolean | "auto" | "preferred")`<br>
223Default: `false`
224
225Controls 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.
226
227```js
228// input
229const foo = require('foo');
230
231// output
232import * as foo from 'foo';
233```
234
235This 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:
236
237- 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.
238- 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:
239
240 ```js
241 // input: main.js
242 const dep = require('./dep.js');
243 console.log(dep.default);
244
245 // input: dep.js
246 export default 'foo';
247
248 // output
249 var dep = 'foo';
250
251 var dep$1 = /*#__PURE__*/ Object.freeze({
252 __proto__: null,
253 default: dep
254 });
255
256 console.log(dep$1.default);
257 ```
258
259For 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:
260
261- `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.
262
263 ```js
264 // input
265 const dep = require('dep');
266 console.log(dep);
267
268 // output
269 import * as dep$1 from 'dep';
270
271 function getAugmentedNamespace(n) {
272 var a = Object.defineProperty({}, '__esModule', { value: true });
273 Object.keys(n).forEach(function (k) {
274 var d = Object.getOwnPropertyDescriptor(n, k);
275 Object.defineProperty(
276 a,
277 k,
278 d.get
279 ? d
280 : {
281 enumerable: true,
282 get: function () {
283 return n[k];
284 }
285 }
286 );
287 });
288 return a;
289 }
290
291 var dep = /*@__PURE__*/ getAugmentedNamespace(dep$1);
292
293 console.log(dep);
294 ```
295
296- `"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.
297
298 ```js
299 // output
300 import * as dep from 'dep';
301
302 console.log(dep);
303 ```
304
305- `"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:
306
307 ```js
308 // output
309 import * as dep$1 from 'dep';
310
311 function getDefaultExportFromNamespaceIfNotNamed(n) {
312 return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1
313 ? n['default']
314 : n;
315 }
316
317 var dep = getDefaultExportFromNamespaceIfNotNamed(dep$1);
318
319 console.log(dep);
320 ```
321
322- `"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:
323
324 ```js
325 // output
326 import * as dep$1 from 'dep';
327
328 function getDefaultExportFromNamespaceIfPresent(n) {
329 return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
330 }
331
332 var dep = getDefaultExportFromNamespaceIfPresent(dep$1);
333
334 console.log(dep);
335 ```
336
337- `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:
338
339 ```js
340 // output
341 import dep from 'dep';
342
343 console.log(dep);
344 ```
345
346To 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.
347
348## Using with @rollup/plugin-node-resolve
349
350Since 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):
351
352```js
353// rollup.config.js
354import resolve from '@rollup/plugin-node-resolve';
355import commonjs from '@rollup/plugin-commonjs';
356
357export default {
358 input: 'main.js',
359 output: {
360 file: 'bundle.js',
361 format: 'iife',
362 name: 'MyModule'
363 },
364 plugins: [resolve(), commonjs()]
365};
366```
367
368## Usage with symlinks
369
370Symlinks 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:
371
372```js
373commonjs({
374 include: /node_modules/
375});
376```
377
378Whether 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.
379
380## Strict mode
381
382ES 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.
383
384Luckily, 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.
385
386## Inter-plugin-communication
387
388This 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:
389
390```js
391function cjsDetectionPlugin() {
392 return {
393 name: 'cjs-detection',
394 moduleParsed({
395 id,
396 meta: {
397 commonjs: { isCommonJS }
398 }
399 }) {
400 console.log(`File ${id} is CommonJS: ${isCommonJS}`);
401 }
402 };
403}
404```
405
406## Meta
407
408[CONTRIBUTING](/.github/CONTRIBUTING.md)
409
410[LICENSE (MIT)](/LICENSE)