From da5ba54087fca4cfdc2c43436bc723faf29da811 Mon Sep 17 00:00:00 2001 From: zanminkian Date: Mon, 17 Apr 2023 11:37:03 +0000 Subject: [PATCH] feat(plugin): allow some one-line arrow functions --- .../src/rules/top-level-function.test.ts | 25 ++++++++++++++++++- .../src/rules/top-level-function.ts | 11 ++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/packages/eslint-plugin-antfu/src/rules/top-level-function.test.ts b/packages/eslint-plugin-antfu/src/rules/top-level-function.test.ts index 06c671b1c5..dc4030ae0e 100644 --- a/packages/eslint-plugin-antfu/src/rules/top-level-function.test.ts +++ b/packages/eslint-plugin-antfu/src/rules/top-level-function.test.ts @@ -17,15 +17,38 @@ const valids = [ // allow export default 'export default () => {}', 'export default defineConfig(() => {})', + 'const foo = (x, y) => x + y', + 'const foo = (x) => `x: ${x}`', + 'const foo = () => \'hello\'', + 'const foo = () => 123', + 'const foo = () => false', + 'const foo = () => /abcd/', + 'const foo = () => undefined', + 'const foo = () => null', + 'const foo = () => String(123)', + 'const foo = async (x, y) => x + y', + 'const foo = async (x) => `x: ${x}`', + 'const foo = async () => \'hello\'', + 'const foo = async () => 123', + 'const foo = async () => false', + 'const foo = async () => /abcd/', + 'const foo = async () => undefined', + 'const foo = async () => null', + 'const foo = async () => String(123)', + // 'const foo = () => ({a: 123})', // Not sure that one-line object expression is valid ] const invalids = [ + [ + 'const foo = (x, y) => \nx + y', + 'function foo (x, y) {\n return x + y\n}', + ], [ 'const foo = (as: string, bar: number) => { return as + bar }', 'function foo (as: string, bar: number) { return as + bar }', ], [ - 'const foo = (as: string, bar: number): Omit => as + bar', + 'const foo = (as: string, bar: number): Omit => \nas + bar', 'function foo (as: string, bar: number): Omit {\n return as + bar\n}', ], [ diff --git a/packages/eslint-plugin-antfu/src/rules/top-level-function.ts b/packages/eslint-plugin-antfu/src/rules/top-level-function.ts index b0ce043038..0120066b26 100644 --- a/packages/eslint-plugin-antfu/src/rules/top-level-function.ts +++ b/packages/eslint-plugin-antfu/src/rules/top-level-function.ts @@ -40,6 +40,17 @@ export default createEslintRule({ return if (declaration.id.typeAnnotation) return + if ( + [ + 'BinaryExpression', + 'Literal', + 'TemplateLiteral', + 'Identifier', + 'CallExpression', + ].includes(declaration.init?.body.type) + && declaration.id?.loc.start.line === declaration.init?.body.loc.end.line + ) + return const arrowFn = declaration.init const body = declaration.init.body