From 506d17c3f79faa6a00daffb6aa5f743b3a012341 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9B=BE=E6=98=8E=E5=81=A5?= Date: Tue, 18 Apr 2023 19:54:50 +0800 Subject: [PATCH] feat(plugin): allow some one-line arrow functions (#172) --- .../src/rules/top-level-function.test.ts | 15 ++++++++++++--- .../src/rules/top-level-function.ts | 5 +++++ 2 files changed, 17 insertions(+), 3 deletions(-) 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..2b484d50d8 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,24 @@ const valids = [ // allow export default 'export default () => {}', 'export default defineConfig(() => {})', + // allow one-line arrow function + 'const foo = (x, y) => x + y', + 'const foo = async (x, y) => x + y', + 'const foo = () => String(123)', + 'const foo = () => ({})', ] 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}', ], [ @@ -33,11 +42,11 @@ const invalids = [ 'export function foo () {}', ], [ - 'export const foo = () => ({})', + 'export const foo = () => \n({})', 'export function foo () {\n return {}\n}', ], [ - 'export const foo = async () => ({})', + 'export const foo = async () => \n({})', 'export async function foo () {\n return {}\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..db485c5dd0 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,11 @@ export default createEslintRule({ return if (declaration.id.typeAnnotation) return + if ( + declaration.init.body.type !== 'BlockStatement' + && declaration.id?.loc.start.line === declaration.init?.body.loc.end.line + ) + return const arrowFn = declaration.init const body = declaration.init.body