Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add prefer-node-protocol rule #97

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/two-rice-look.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"eslint-plugin-import-x": patch
---

feat: add `prefer-node-protocol` rule
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ This plugin intends to support linting of ES2015+ (ES6+) import/export syntax, a
| [no-unassigned-import](docs/rules/no-unassigned-import.md) | Forbid unassigned imports. | | | | | | |
| [order](docs/rules/order.md) | Enforce a convention in module import order. | | | | 🔧 | | |
| [prefer-default-export](docs/rules/prefer-default-export.md) | Prefer a default export if module exports a single name or multiple names. | | | | | | |
| [prefer-node-protocol](docs/rules/prefer-node-protocol.md) | When importing builtin modules, it's better to use the node: protocol. | | | | 🔧 | | |

<!-- end auto-generated rules list -->

Expand Down
62 changes: 62 additions & 0 deletions docs/rules/prefer-node-protocol.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# import-x/prefer-node-protocol

🔧 This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix).

<!-- end auto-generated rule header -->
<!-- Do not manually modify this header. Run: `npm run update:eslint-docs` -->

When importing builtin modules, it's better to use the [`node:` protocol](https://nodejs.org/api/esm.html#node-imports) as it makes it perfectly clear that the package is a Node.js builtin module.

Note that Node.js support for this feature began in:

> v16.0.0, v14.18.0 (`require()`)
>
> v14.13.1, v12.20.0 (`import`)

## Fail

```js
import dgram from 'dgram';
```

```js
export {strict as default} from 'assert';
```

```js
import fs from 'fs/promises';
```

```js
const fs = require('fs');
```

```js
const fs = require('fs/promises');
```

## Pass

```js
import dgram from 'node:dgram';
```

```js
export {strict as default} from 'node:assert';
```

```js
import fs from 'node:fs/promises';
```

```js
import _ from 'lodash';
```

```js
import fs from './fs.js';
```

```js
const fs = require('node:fs/promises');
```
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"build": "tsc -p src",
"clean": "rimraf lib",
"codesandbox:install": "yarn --ignore-engines",
"format": "prettier --write .",
"lint": "run-p lint:*",
"lint:docs": "yarn update:eslint-docs --check",
"lint:es": "eslint . --cache",
Expand Down
4 changes: 3 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import noUselessPathSegments from './rules/no-useless-path-segments'
import noWebpackLoaderSyntax from './rules/no-webpack-loader-syntax'
import order from './rules/order'
import preferDefaultExport from './rules/prefer-default-export'
import preferNodeProtocol from './rules/prefer-node-protocol'
import unambiguous from './rules/unambiguous'
// configs
import type { PluginConfig } from './types'
Expand Down Expand Up @@ -108,7 +109,6 @@ const rules = {
'no-webpack-loader-syntax': noWebpackLoaderSyntax,
order,
'newline-after-import': newlineAfterImport,
'prefer-default-export': preferDefaultExport,
'no-default-export': noDefaultExport,
'no-named-export': noNamedExport,
'no-dynamic-require': noDynamicRequire,
Expand All @@ -118,6 +118,8 @@ const rules = {
'dynamic-import-chunkname': dynamicImportChunkname,
'no-import-module-exports': noImportModuleExports,
'no-empty-named-blocks': noEmptyNamedBlocks,
'prefer-default-export': preferDefaultExport,
'prefer-node-protocol': preferNodeProtocol,

// export
'exports-last': exportsLast,
Expand Down
64 changes: 64 additions & 0 deletions src/rules/prefer-node-protocol.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import type { TSESLint, TSESTree } from '@typescript-eslint/utils'
import { createRule, importType, moduleVisitor } from '../utils'

export = createRule({
name: 'prefer-node-protocol',
meta: {
type: 'problem',
docs: {
category: 'Style guide',
description:
"When importing builtin modules, it's better to use the node: protocol.",
},
schema: [],
messages: {
preferNode: 'Prefer `node:{{moduleName}}` over `{{moduleName}}`.',
},
},
defaultOptions: [],
create(context) {
return moduleVisitor(
(source, node) => {
const moduleName = source.value
if (
importType(moduleName, context) === 'builtin' &&
!(moduleName.startsWith('node:') || /^bun(?::|$)/.test(moduleName))
) {
context.report({
node,
messageId: 'preferNode',
data: {
moduleName,
},
fix: fixer => replaceStringLiteral(fixer, node, 'node:', 0, 0),
})
}
},
{ commonjs: true },
)
},
})

function replaceStringLiteral(
fixer: TSESLint.RuleFixer,
node:
| TSESTree.StringLiteral
| TSESTree.ImportDeclaration
| TSESTree.ExportNamedDeclaration
| TSESTree.ExportAllDeclaration
| TSESTree.CallExpression
| TSESTree.ImportExpression,
text: string,
relativeRangeStart: number,
relativeRangeEnd: number,
) {
const firstCharacterIndex = node.range[0] + 1
const start = Number.isInteger(relativeRangeEnd)
? relativeRangeStart + firstCharacterIndex
: firstCharacterIndex
const end = Number.isInteger(relativeRangeEnd)
? relativeRangeEnd + firstCharacterIndex
: node.range[1] - 1

return fixer.replaceTextRange([start, end], text)
}
48 changes: 48 additions & 0 deletions test/rules/prefer-node-protocol.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { TSESLint } from '@typescript-eslint/utils'

import { test } from '../utils'

import rule from 'eslint-plugin-import-x/rules/no-nodejs-modules'

const ruleTester = new TSESLint.RuleTester()

const error = (message: string) => ({
message,
})

ruleTester.run('no-nodejs-modules', rule, {
valid: [
test({ code: 'import _ from "lodash"' }),
test({ code: 'import find from "lodash.find"' }),
test({ code: 'import foo from "./foo"' }),
test({ code: 'import foo from "../foo"' }),
test({ code: 'import foo from "foo"' }),
test({ code: 'import foo from "./"' }),
test({ code: 'import foo from "@scope/foo"' }),
test({ code: 'var _ = require("lodash")' }),
test({ code: 'var find = require("lodash.find")' }),
test({ code: 'var foo = require("./foo")' }),
test({ code: 'var foo = require("../foo")' }),
test({ code: 'var foo = require("foo")' }),
test({ code: 'var foo = require("./")' }),
test({ code: 'var foo = require("@scope/foo")' }),
],
invalid: [
test({
code: 'import path from "path"',
errors: [error('Do not import Node.js builtin module "path"')],
}),
test({
code: 'import { readFileSync } from "fs"',
errors: [error('Do not import Node.js builtin module "fs"')],
}),
test({
code: 'var path = require("path")',
errors: [error('Do not import Node.js builtin module "path"')],
}),
test({
code: 'var readFileSync = require("fs").readFileSync',
errors: [error('Do not import Node.js builtin module "fs"')],
}),
],
})