Skip to content

Commit

Permalink
Add guide for CommonJS (closes #465)
Browse files Browse the repository at this point in the history
  • Loading branch information
webpro committed Jan 22, 2024
1 parent 9264819 commit 2d17925
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
66 changes: 66 additions & 0 deletions packages/docs/src/content/docs/guides/commonjs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
---
title: Working with CommonJS
---

CommonJS is the JavaScript module system using `require()` and `module.exports`
statements.

Knip works well with CommonJS. You don't need to use ES Modules or a
`tsconfig.json` to use Knip. But due to the dynamic nature of CommonJS, we'll
have to agree on a few conventions. Those conventions are designed to minimize
impact on existing codebases, improve consistency, and ease migration to ES
Modules or TypeScript.

For **named exports**, the recommendation is to assign keys to `module.exports`:

```js
const B = function () {};

module.exports.A = { option: true };
module.exports.B = B;
```

Alternatively, assign an object with ONLY shorthand property assignments to
`module.exports`:

```js
const A = function () {};
const B = { option: true };

module.exports = { A, B };
```

Anything else assigned to `module.exports` is considered a default export, and
should be imported as such.

The following **default import** of the **named exports** above will result in
all those exports reported as unused, even when referenced like below:

```js
const DefaultImport = require('./common.js');
const runtime = [DefaultImport.A, DefaultImport.B];
```

Instead, do this:

```js
const { A, B } = require('./common.js');
const runtime = [A, B];
```

Not recommended per se, but the following import syntax also results in the
named export `A` being used:

```js
const runtime = [require('./common.js').A];
```

Add a non-shorthand property to turn the named object notation into a single
**default export**:

```js
const A = function () {};
const B = { option: true };

module.exports = { __esModule: true, A, B };
```
2 changes: 2 additions & 0 deletions packages/docs/src/content/docs/guides/handling-issues.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
---
title: Handling Issues
sidebar:
order: 2
---

A long list of unused items can be frustrating. The list may contain false
Expand Down

0 comments on commit 2d17925

Please sign in to comment.