Skip to content

chore(eslint-plugin): deprecate no-var-requires in favor of no-require-imports #8334

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

Merged
merged 35 commits into from
May 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
e364b60
chore(eslint-plugin): deprecate no-var-requires in favor of no-requir…
arkapratimc Jan 30, 2024
2742433
chore: address CI failures
arkapratimc Feb 1, 2024
c108ea6
chore: more CI failures
arkapratimc Feb 1, 2024
5393062
chore: small miss
arkapratimc Feb 1, 2024
a5c03b7
chore: address ci failures
arkapratimc Feb 1, 2024
0354320
chore: few more tests
arkapratimc Feb 6, 2024
af69110
Merge branch 'main' into issue-8092
arkapratimc Feb 6, 2024
0ab1f78
chore: update docs
arkapratimc Feb 6, 2024
145c4e5
chore: address reviews
arkapratimc Feb 8, 2024
a39539e
Merge branch 'issue-8092' of github.com:arka1002/typescript-eslint in…
arkapratimc Feb 8, 2024
61baa81
missed one test
arkapratimc Feb 12, 2024
091385e
Merge branch 'v8' into issue-8092
arkapratimc Mar 20, 2024
2815ab4
chore: fix tests
arkapratimc Mar 21, 2024
7f8466c
chore: add recommended
arkapratimc Mar 21, 2024
04d7887
chore: lint errors
arkapratimc Mar 21, 2024
39cc57a
chore: address reviews
arkapratimc Mar 21, 2024
c060a35
chore: small miss
arkapratimc Mar 21, 2024
b2a0081
chore: mistake
arkapratimc Mar 21, 2024
cf12e82
chore: eslint comments
arkapratimc Mar 31, 2024
9283877
chore: apply suggestions from code review
arkapratimc Apr 1, 2024
8253e21
feat(typescript-estree): remove slow deprecated and isolated programs…
JoshuaKGoldberg Apr 15, 2024
faa74c5
fix(typescript-estree): add TSEnumBody node for TSEnumDeclaration bod…
JoshuaKGoldberg Apr 15, 2024
69e337f
Merge branch 'v8' into issue-8092
arkapratimc Apr 16, 2024
a5a9fa0
Merge branch 'issue-8092' of github.com:arka1002/typescript-eslint in…
arkapratimc Apr 16, 2024
da382b8
chore: snapshots
arkapratimc Apr 16, 2024
9cafe31
chore: eslint comments
arkapratimc Apr 19, 2024
baf469a
Merge branch 'v8'
JoshuaKGoldberg Apr 23, 2024
346fed1
chore: address reviews
arkapratimc Apr 25, 2024
9a76d9e
chore: update docs
arkapratimc Apr 26, 2024
a6a3307
chore: docs
arkapratimc May 26, 2024
594afbf
chore: refactor
arkapratimc May 26, 2024
ee452e4
Merge branch 'v8' into issue-8092
arkapratimc May 26, 2024
4a6216c
Merge branch 'v8' into issue-8092
bradzacher May 28, 2024
b757092
Update pack-packages.ts
bradzacher May 28, 2024
05956d8
Format pack-packages.ts ugh
bradzacher May 28, 2024
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
6 changes: 6 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,12 @@ export default tseslint.config(
ignorePrimitives: true,
},
],
'@typescript-eslint/no-require-imports': [
'error',
{
allow: ['/package\\.json$'],
},
],

//
// Internal repo rules
Expand Down
3 changes: 2 additions & 1 deletion packages/ast-spec/tests/fixtures.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fs from 'fs';
import glob = require('glob');
import * as glob from 'glob';
import makeDir from 'make-dir';
import path from 'path';

Expand Down Expand Up @@ -66,6 +66,7 @@ const FIXTURES: readonly Fixture[] = [...VALID_FIXTURES, ...ERROR_FIXTURES].map(
absolute,
config: ((): ASTFixtureConfig => {
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require(configPath).default;
} catch {
return {};
Expand Down
29 changes: 28 additions & 1 deletion packages/eslint-plugin/docs/rules/no-require-imports.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ import * as lib3 from 'lib3';

### `allow`

A array of strings. These strings will be compiled into regular expressions with the `u` flag and be used to test against the imported path. A common use case is to allow importing `package.json`. This is because `package.json` commonly lives outside of the TS root directory, so statically importing it would lead to root directory conflicts, especially with `resolveJsonModule` enabled. You can also use it to allow importing any JSON if your environment doesn't support JSON modules, or use it for other cases where `import` statements cannot work.
An array of strings. These strings will be compiled into regular expressions with the `u` flag and be used to test against the imported path. A common use case is to allow importing `package.json`. This is because `package.json` commonly lives outside of the TS root directory, so statically importing it would lead to root directory conflicts, especially with `resolveJsonModule` enabled. You can also use it to allow importing any JSON if your environment doesn't support JSON modules, or use it for other cases where `import` statements cannot work.

With `{allow: ['/package\\.json$']}`:

Expand All @@ -59,6 +59,33 @@ console.log(require('../package.json').version);
</TabItem>
</Tabs>

### `allowAsImport`

When set to `true`, the `import x = require(...)` declaration won't be reported.
This is useful if you use certain module options that require strict CommonJS interop semantics.

With `{allowAsImport: true}`:

<Tabs>
<TabItem value="❌ Incorrect">

```ts option='{ "allowAsImport": true }'
var foo = require('foo');
const foo = require('foo');
let foo = require('foo');
```

</TabItem>
<TabItem value="✅ Correct">

```ts option='{ "allowAsImport": true }'
import foo = require('foo');
import foo from 'foo';
```

</TabItem>
</Tabs>

## When Not To Use It

If your project frequently uses older CommonJS `require`s, then this rule might not be applicable to you.
Expand Down
6 changes: 6 additions & 0 deletions packages/eslint-plugin/docs/rules/no-var-requires.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ import TabItem from '@theme/TabItem';
>
> See **https://typescript-eslint.io/rules/no-var-requires** for documentation.

:::danger Deprecated

This rule has been deprecated in favour of the [`@typescript-eslint/no-require-imports`](./no-require-imports.mdx) rule.

:::

In other words, the use of forms such as `var foo = require("foo")` are banned. Instead use ES6 style imports or `import foo = require("foo")` imports.

## Examples
Expand Down
1 change: 0 additions & 1 deletion packages/eslint-plugin/src/configs/all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,6 @@ export = {
'@typescript-eslint/no-useless-constructor': 'error',
'@typescript-eslint/no-useless-empty-export': 'error',
'@typescript-eslint/no-useless-template-literals': 'error',
'@typescript-eslint/no-var-requires': 'error',
'@typescript-eslint/non-nullable-type-assertion-style': 'error',
'no-throw-literal': 'off',
'@typescript-eslint/only-throw-error': 'error',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export = {
'@typescript-eslint/no-namespace': 'error',
'@typescript-eslint/no-non-null-asserted-optional-chain': 'error',
'@typescript-eslint/no-redundant-type-constituents': 'error',
'@typescript-eslint/no-require-imports': 'error',
'@typescript-eslint/no-this-alias': 'error',
'@typescript-eslint/no-unnecessary-type-assertion': 'error',
'@typescript-eslint/no-unnecessary-type-constraint': 'error',
Expand All @@ -47,7 +48,6 @@ export = {
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': 'error',
'@typescript-eslint/no-useless-template-literals': 'error',
'@typescript-eslint/no-var-requires': 'error',
'no-throw-literal': 'off',
'@typescript-eslint/only-throw-error': 'error',
'@typescript-eslint/prefer-as-const': 'error',
Expand Down
2 changes: 1 addition & 1 deletion packages/eslint-plugin/src/configs/recommended.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@ export = {
'@typescript-eslint/no-misused-new': 'error',
'@typescript-eslint/no-namespace': 'error',
'@typescript-eslint/no-non-null-asserted-optional-chain': 'error',
'@typescript-eslint/no-require-imports': 'error',
'@typescript-eslint/no-this-alias': 'error',
'@typescript-eslint/no-unnecessary-type-constraint': 'error',
'@typescript-eslint/no-unsafe-declaration-merging': 'error',
'no-unused-expressions': 'off',
'@typescript-eslint/no-unused-expressions': 'error',
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': 'error',
'@typescript-eslint/no-var-requires': 'error',
'@typescript-eslint/prefer-as-const': 'error',
'@typescript-eslint/prefer-namespace-keyword': 'error',
'@typescript-eslint/triple-slash-reference': 'error',
Expand Down
2 changes: 1 addition & 1 deletion packages/eslint-plugin/src/configs/strict-type-checked.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export = {
'@typescript-eslint/no-non-null-asserted-optional-chain': 'error',
'@typescript-eslint/no-non-null-assertion': 'error',
'@typescript-eslint/no-redundant-type-constituents': 'error',
'@typescript-eslint/no-require-imports': 'error',
'@typescript-eslint/no-this-alias': 'error',
'@typescript-eslint/no-unnecessary-boolean-literal-compare': 'error',
'@typescript-eslint/no-unnecessary-condition': 'error',
Expand All @@ -63,7 +64,6 @@ export = {
'no-useless-constructor': 'off',
'@typescript-eslint/no-useless-constructor': 'error',
'@typescript-eslint/no-useless-template-literals': 'error',
'@typescript-eslint/no-var-requires': 'error',
'no-throw-literal': 'off',
'@typescript-eslint/only-throw-error': 'error',
'@typescript-eslint/prefer-as-const': 'error',
Expand Down
2 changes: 1 addition & 1 deletion packages/eslint-plugin/src/configs/strict.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export = {
'@typescript-eslint/no-non-null-asserted-nullish-coalescing': 'error',
'@typescript-eslint/no-non-null-asserted-optional-chain': 'error',
'@typescript-eslint/no-non-null-assertion': 'error',
'@typescript-eslint/no-require-imports': 'error',
'@typescript-eslint/no-this-alias': 'error',
'@typescript-eslint/no-unnecessary-type-constraint': 'error',
'@typescript-eslint/no-unsafe-declaration-merging': 'error',
Expand All @@ -38,7 +39,6 @@ export = {
'@typescript-eslint/no-unused-vars': 'error',
'no-useless-constructor': 'off',
'@typescript-eslint/no-useless-constructor': 'error',
'@typescript-eslint/no-var-requires': 'error',
'@typescript-eslint/prefer-as-const': 'error',
'@typescript-eslint/prefer-literal-enum-member': 'error',
'@typescript-eslint/prefer-namespace-keyword': 'error',
Expand Down
24 changes: 18 additions & 6 deletions packages/eslint-plugin/src/rules/no-require-imports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import * as util from '../util';

type Options = [
{
allow: string[];
allow?: string[];
allowAsImport?: boolean;
},
];
type MessageIds = 'noRequireImports';
Expand All @@ -16,6 +17,7 @@ export default util.createRule<Options, MessageIds>({
type: 'problem',
docs: {
description: 'Disallow invocation of `require()`',
recommended: 'recommended',
},
schema: [
{
Expand All @@ -26,6 +28,10 @@ export default util.createRule<Options, MessageIds>({
items: { type: 'string' },
description: 'Patterns of import paths to allow requiring from.',
},
allowAsImport: {
type: 'boolean',
description: 'Allows `require` statements in import declarations.',
},
},
additionalProperties: false,
},
Expand All @@ -34,13 +40,14 @@ export default util.createRule<Options, MessageIds>({
noRequireImports: 'A `require()` style import is forbidden.',
},
},
defaultOptions: [{ allow: [] }],
defaultOptions: [{ allow: [], allowAsImport: false }],
create(context, options) {
const allowPatterns = options[0].allow.map(
const allowAsImport = options[0].allowAsImport;
const allowPatterns = options[0].allow?.map(
pattern => new RegExp(pattern, 'u'),
);
function isImportPathAllowed(importPath: string): boolean {
return allowPatterns.some(pattern => importPath.match(pattern));
function isImportPathAllowed(importPath: string): boolean | undefined {
return allowPatterns?.some(pattern => importPath.match(pattern));
}
function isStringOrTemplateLiteral(node: TSESTree.Node): boolean {
return (
Expand All @@ -64,7 +71,6 @@ export default util.createRule<Options, MessageIds>({
context.sourceCode.getScope(node),
'require',
);

// ignore non-global require usage as it's something user-land custom instead
// of the commonjs standard
if (!variable?.identifiers.length) {
Expand All @@ -81,6 +87,12 @@ export default util.createRule<Options, MessageIds>({
return;
}
}
if (
allowAsImport &&
node.parent.type === AST_NODE_TYPES.TSImportEqualsDeclaration
) {
return;
}
context.report({
node,
messageId: 'noRequireImports',
Expand Down
3 changes: 2 additions & 1 deletion packages/eslint-plugin/src/rules/no-var-requires.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@ type MessageIds = 'noVarReqs';
export default createRule<Options, MessageIds>({
name: 'no-var-requires',
meta: {
deprecated: true,
replacedBy: ['@typescript-eslint/no-require-imports'],
type: 'problem',
docs: {
description: 'Disallow `require` statements except in import statements',
recommended: 'recommended',
},
messages: {
noVarReqs: 'Require statement not part of import statement.',
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading