Giter VIP home page Giter VIP logo

eslint-config's Introduction

@antfu/eslint-config

npm code style

  • Single quotes, no semi
  • Auto fix for formatting (aimed to be used standalone without Prettier)
  • Sorted imports, dangling commas
  • Reasonable defaults, best practices, only one line of config
  • Designed to work with TypeScript, JSX, Vue out-of-box
  • Lints also for json, yaml, toml, markdown
  • Opinionated, but very customizable
  • ESLint Flat config, compose easily!
  • Using ESLint Stylistic
  • Respects .gitignore by default
  • Optional React, Svelte, UnoCSS, Astro, Solid support
  • Optional formatters support for CSS, HTML, etc.
  • Style principle: Minimal for reading, stable for diff, consistent

Important

Since v1.0.0, this config is rewritten to the new ESLint Flat config, check the release note for more details.

Usage

Starter Wizard

We provided a CLI tool to help you set up your project, or migrate from the legacy config to the new flat config with one command.

npx @antfu/eslint-config@latest

Manual Install

If you prefer to set up manually:

pnpm i -D eslint @antfu/eslint-config

And create eslint.config.mjs in your project root:

// eslint.config.mjs
import antfu from '@antfu/eslint-config'

export default antfu()
Combined with legacy config:

If you still use some configs from the legacy eslintrc format, you can use the @eslint/eslintrc package to convert them to the flat config.

// eslint.config.mjs
import antfu from '@antfu/eslint-config'
import { FlatCompat } from '@eslint/eslintrc'

const compat = new FlatCompat()

export default antfu(
  {
    ignores: [],
  },

  // Legacy config
  ...compat.config({
    extends: [
      'eslint:recommended',
      // Other extends...
    ],
  })

  // Other flat configs...
)

Note that .eslintignore no longer works in Flat config, see customization for more details.

Add script for package.json

For example:

{
  "scripts": {
    "lint": "eslint .",
    "lint:fix": "eslint . --fix"
  }
}

VS Code support (auto fix on save)

Install VS Code ESLint extension

Add the following settings to your .vscode/settings.json:

{
  // Enable the ESlint flat config support
  "eslint.experimental.useFlatConfig": true,

  // Disable the default formatter, use eslint instead
  "prettier.enable": false,
  "editor.formatOnSave": false,

  // Auto fix
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "explicit",
    "source.organizeImports": "never"
  },

  // Silent the stylistic rules in you IDE, but still auto fix them
  "eslint.rules.customizations": [
    { "rule": "style/*", "severity": "off" },
    { "rule": "format/*", "severity": "off" },
    { "rule": "*-indent", "severity": "off" },
    { "rule": "*-spacing", "severity": "off" },
    { "rule": "*-spaces", "severity": "off" },
    { "rule": "*-order", "severity": "off" },
    { "rule": "*-dangle", "severity": "off" },
    { "rule": "*-newline", "severity": "off" },
    { "rule": "*quotes", "severity": "off" },
    { "rule": "*semi", "severity": "off" }
  ],

  // Enable eslint for all supported languages
  "eslint.validate": [
    "javascript",
    "javascriptreact",
    "typescript",
    "typescriptreact",
    "vue",
    "html",
    "markdown",
    "json",
    "jsonc",
    "yaml",
    "toml",
    "gql",
    "graphql"
  ]
}

Customization

Since v1.0, we migrated to ESLint Flat config. It provides much better organization and composition.

Normally you only need to import the antfu preset:

// eslint.config.js
import antfu from '@antfu/eslint-config'

export default antfu()

And that's it! Or you can configure each integration individually, for example:

// eslint.config.js
import antfu from '@antfu/eslint-config'

export default antfu({
  // Enable stylistic formatting rules
  // stylistic: true,

  // Or customize the stylistic rules
  stylistic: {
    indent: 2, // 4, or 'tab'
    quotes: 'single', // or 'double'
  },

  // TypeScript and Vue are auto-detected, you can also explicitly enable them:
  typescript: true,
  vue: true,

  // Disable jsonc and yaml support
  jsonc: false,
  yaml: false,

  // `.eslintignore` is no longer supported in Flat config, use `ignores` instead
  ignores: [
    '**/fixtures',
    // ...globs
  ]
})

The antfu factory function also accepts any number of arbitrary custom config overrides:

// eslint.config.js
import antfu from '@antfu/eslint-config'

export default antfu(
  {
    // Configures for antfu's config
  },

  // From the second arguments they are ESLint Flat Configs
  // you can have multiple configs
  {
    files: ['**/*.ts'],
    rules: {},
  },
  {
    rules: {},
  },
)

Going more advanced, you can also import fine-grained configs and compose them as you wish:

Advanced Example

We wouldn't recommend using this style in general unless you know exactly what they are doing, as there are shared options between configs and might need extra care to make them consistent.

// eslint.config.js
import {
  combine,
  comments,
  ignores,
  imports,
  javascript,
  jsdoc,
  jsonc,
  markdown,
  node,
  sortPackageJson,
  sortTsconfig,
  stylistic,
  toml,
  typescript,
  unicorn,
  vue,
  yaml,
} from '@antfu/eslint-config'

export default combine(
  ignores(),
  javascript(/* Options */),
  comments(),
  node(),
  jsdoc(),
  imports(),
  unicorn(),
  typescript(/* Options */),
  stylistic(),
  vue(),
  jsonc(),
  yaml(),
  toml(),
  markdown(),
)

Check out the configs and factory for more details.

Thanks to sxzz/eslint-config for the inspiration and reference.

Plugins Renaming

Since flat config requires us to explicitly provide the plugin names (instead of the mandatory convention from npm package name), we renamed some plugins to make the overall scope more consistent and easier to write.

New Prefix Original Prefix Source Plugin
import/* import-x/* eslint-plugin-import-x
node/* n/* eslint-plugin-n
yaml/* yml/* eslint-plugin-yml
ts/* @typescript-eslint/* @typescript-eslint/eslint-plugin
style/* @stylistic/* @stylistic/eslint-plugin
test/* vitest/* eslint-plugin-vitest
test/* no-only-tests/* eslint-plugin-no-only-tests

When you want to override rules, or disable them inline, you need to update to the new prefix:

-// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
+// eslint-disable-next-line ts/consistent-type-definitions
type foo = { bar: 2 }

Note

About plugin renaming - it is actually rather a dangrous move that might leading to potential naming collisions, pointed out here and here. As this config also very personal and opinionated, I ambitiously position this config as the only "top-level" config per project, that might pivots the taste of how rules are named.

This config cares more about the user-facings DX, and try to ease out the implementation details. For example, users could keep using the semantic import/order without ever knowing the underlying plugin has migrated twice to eslint-plugin-i and then to eslint-plugin-import-x. User are also not forced to migrate to the implicit i/order halfway only because we swapped the implementation to a fork.

That said, it's probably still not a good idea. You might not want to doing this if you are maintaining your own eslint config.

Feel free to open issues if you want to combine this config with some other config presets but faced naming collisions. I am happy to figure out a way to make them work. But at this moment I have no plan to revert the renaming.

Since v2.9.0, this preset will automatically rename the plugins also for your custom configs. You can use the original prefix to override the rules directly.

Rules Overrides

Certain rules would only be enabled in specific files, for example, ts/* rules would only be enabled in .ts files and vue/* rules would only be enabled in .vue files. If you want to override the rules, you need to specify the file extension:

// eslint.config.js
import antfu from '@antfu/eslint-config'

export default antfu(
  {
    vue: true,
    typescript: true
  },
  {
    // Remember to specify the file glob here, otherwise it might cause the vue plugin to handle non-vue files
    files: ['**/*.vue'],
    rules: {
      'vue/operator-linebreak': ['error', 'before'],
    },
  },
  {
    // Without `files`, they are general rules for all files
    rules: {
      'style/semi': ['error', 'never'],
    },
  }
)

We also provided the overrides options in each integration to make it easier:

// eslint.config.js
import antfu from '@antfu/eslint-config'

export default antfu({
  vue: {
    overrides: {
      'vue/operator-linebreak': ['error', 'before'],
    },
  },
  typescript: {
    overrides: {
      'ts/consistent-type-definitions': ['error', 'interface'],
    },
  },
  yaml: {
    overrides: {
      // ...
    },
  },
})

Config Composer

Since v2.10.0, the factory function antfu() returns a FlatConfigComposer object from eslint-flat-config-utils where you can chain the methods to compose the config even more flexibly.

// eslint.config.js
import antfu from '@antfu/eslint-config'

export default antfu()
  .prepend(
    // some configs before the main config
  )
  // overrides any named configs
  .override(
    'antfu/imports',
    {
      rules: {
        'import/order': ['error', { 'newlines-between': 'always' }],
      }
    }
  )
  // rename plugin prefixes
  .renamePlugins({
    'old-prefix': 'new-prefix',
    // ...
  })
// ...

Vue

Vue support is detected automatically by checking if vue is installed in your project. You can also explicitly enable/disable it:

// eslint.config.js
import antfu from '@antfu/eslint-config'

export default antfu({
  vue: true
})

Vue 2

We have limited support for Vue 2 (as it's already reached EOL). If you are still using Vue 2, you can configure it manually by setting vueVersion to 2:

// eslint.config.js
import antfu from '@antfu/eslint-config'

export default antfu({
  vue: {
    vueVersion: 2
  },
})

As it's in maintenance mode, we only accept bug fixes for Vue 2. It might also be removed in the future when eslint-plugin-vue drops support for Vue 2. We recommend upgrading to Vue 3 if possible.

Optional Configs

We provide some optional configs for specific use cases, that we don't include their dependencies by default.

Formatters

Use external formatters to format files that ESLint cannot handle yet (.css, .html, etc). Powered by eslint-plugin-format.

// eslint.config.js
import antfu from '@antfu/eslint-config'

export default antfu({
  formatters: {
    /**
     * Format CSS, LESS, SCSS files, also the `<style>` blocks in Vue
     * By default uses Prettier
     */
    css: true,
    /**
     * Format HTML files
     * By default uses Prettier
     */
    html: true,
    /**
     * Format Markdown files
     * Supports Prettier and dprint
     * By default uses Prettier
     */
    markdown: 'prettier'
  }
})

Running npx eslint should prompt you to install the required dependencies, otherwise, you can install them manually:

npm i -D eslint-plugin-format

React

To enable React support, you need to explicitly turn it on:

// eslint.config.js
import antfu from '@antfu/eslint-config'

export default antfu({
  react: true,
})

Running npx eslint should prompt you to install the required dependencies, otherwise, you can install them manually:

npm i -D @eslint-react/eslint-plugin eslint-plugin-react-hooks eslint-plugin-react-refresh

Svelte

To enable svelte support, you need to explicitly turn it on:

// eslint.config.js
import antfu from '@antfu/eslint-config'

export default antfu({
  svelte: true,
})

Running npx eslint should prompt you to install the required dependencies, otherwise, you can install them manually:

npm i -D eslint-plugin-svelte

Astro

To enable astro support, you need to explicitly turn it on:

// eslint.config.js
import antfu from '@antfu/eslint-config'

export default antfu({
  astro: true,
})

Running npx eslint should prompt you to install the required dependencies, otherwise, you can install them manually:

npm i -D eslint-plugin-astro

Solid

To enable Solid support, you need to explicitly turn it on:

// eslint.config.js
import antfu from '@antfu/eslint-config'

export default antfu({
  solid: true,
})

Running npx eslint should prompt you to install the required dependencies, otherwise, you can install them manually:

npm i -D eslint-plugin-solid

UnoCSS

To enable UnoCSS support, you need to explicitly turn it on:

// eslint.config.js
import antfu from '@antfu/eslint-config'

export default antfu({
  unocss: true,
})

Running npx eslint should prompt you to install the required dependencies, otherwise, you can install them manually:

npm i -D @unocss/eslint-plugin

Optional Rules

This config also provides some optional plugins/rules for extended usage.

perfectionist (sorting)

This plugin eslint-plugin-perfectionist allows you to sort object keys, imports, etc, with auto-fix.

The plugin is installed, but no rules are enabled by default.

It's recommended to opt-in on each file individually using configuration comments.

/* eslint perfectionist/sort-objects: "error" */
const objectWantedToSort = {
  a: 2,
  b: 1,
  c: 3,
}

Type Aware Rules

You can optionally enable the type aware rules by passing the options object to the typescript config:

// eslint.config.js
import antfu from '@antfu/eslint-config'

export default antfu({
  typescript: {
    tsconfigPath: 'tsconfig.json',
  },
})

Editor Specific Disables

Some rules are disabled when inside ESLint IDE integrations, namely unused-imports/no-unused-imports test/no-only-tests

This is to prevent unused imports from getting removed by the IDE during refactoring to get a better developer experience. Those rules will be applied when you run ESLint in the terminal or Lint Staged. If you don't want this behavior, you can disable them:

// eslint.config.js
import antfu from '@antfu/eslint-config'

export default antfu({
  isInEditor: false
})

Lint Staged

If you want to apply lint and auto-fix before every commit, you can add the following to your package.json:

{
  "simple-git-hooks": {
    "pre-commit": "pnpm lint-staged"
  },
  "lint-staged": {
    "*": "eslint --fix"
  }
}

and then

npm i -D lint-staged simple-git-hooks

// to active the hooks
npx simple-git-hooks

View what rules are enabled

I built a visual tool to help you view what rules are enabled in your project and apply them to what files, @eslint/config-inspector

Go to your project root that contains eslint.config.js and run:

npx @eslint/config-inspector

Versioning Policy

This project follows Semantic Versioning for releases. However, since this is just a config and involves opinions and many moving parts, we don't treat rules changes as breaking changes.

Changes Considered as Breaking Changes

  • Node.js version requirement changes
  • Huge refactors that might break the config
  • Plugins made major changes that might break the config
  • Changes that might affect most of the codebases

Changes Considered as Non-breaking Changes

  • Enable/disable rules and plugins (that might become stricter)
  • Rules options changes
  • Version bumps of dependencies

Badge

If you enjoy this code style, and would like to mention it in your project, here is the badge you can use:

[![code style](https://antfu.me/badge-code-style.svg)](https://github.com/antfu/eslint-config)

code style

FAQ

Prettier?

Why I don't use Prettier

Well, you can still use Prettier to format files that are not supported well by ESLint yet, such as .css, .html, etc. See formatters for more details.

dprint?

dprint is also a great formatter that with more abilities to customize. However, it's in the same model as Prettier which reads the AST and reprints the code from scratch. This means it's similar to Prettier, which ignores the original line breaks and might also cause the inconsistent diff. So in general, we prefer to use ESLint to format and lint JavaScript/TypeScript code.

Meanwhile, we do have dprint integrations for formatting other files such as .md. See formatters for more details.

How to format CSS?

You can opt-in to the formatters feature to format your CSS. Note that it's only doing formatting, but not linting. If you want proper linting support, give stylelint a try.

Top-level Function Style, etc.

I am a very opinionated person, so as this config. I prefer the top-level functions always using the function declaration over arrow functions; I prefer one-line if statements without braces and always wraps, and so on. I even wrote some custom rules to enforce them.

I know they are not necessarily the popular opinions. If you really want to get rid of them, you can disable them with:

import antfu from '@antfu/eslint-config'

export default antfu({
  lessOpinionated: true
})

I prefer XXX...

Sure, you can configure and override rules locally in your project to fit your needs. If that still does not work for you, you can always fork this repo and maintain your own.

Check Also

License

MIT License © 2019-PRESENT Anthony Fu

eslint-config's People

Contributors

antfu avatar cloydlau avatar debbl avatar dimava avatar holazz avatar hyoban avatar injurka avatar ivanmaxlogiudice avatar kaivanwong avatar kecrily avatar kirklin avatar mutoe avatar nikkolast88 avatar oumarbarry avatar pinkchampagne17 avatar pscldev avatar qin-guan avatar qiront avatar renovate-bot avatar renovate[bot] avatar rubiin avatar simon-he95 avatar so1ve avatar sxzz avatar thenbe avatar topplethenun avatar yunsii avatar yunyoujun avatar zanminkian avatar ziloen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

eslint-config's Issues

Usage with Solid

Hi, how can we prevent errors when using this config in Solidjs? It shows props error for react even when the tsconfig looks like

{
     "jsx": "preserve",
    "jsxImportSource": "solid-js",
}

chore: ignore

I'm sorry for send issue to wrong repo, pls delete this issue

Update to typescript 4.4

Hi, Antfu! Thank you for your lib!
Can you update typescript to 4.4version at packages/typescript?
Because some new features at typescript eslint marks as error

THanks!

question: introducing Prettier?

I found that for having consistent commits (extra newline, if/else new curlies, etc.) adding prettier on top avoids having two different programmers have an inconsistent style. So far there are virtually no conflicts, my configuration is as follows:

image

Broke on v0.19.0

Oops! Something went wrong! :(

ESLint: 8.12.0

ESLint couldn't find the config "./standard" to extend from. Please check that the name of the config is correct.

standard.js file missing in package

Prototype Pollution in JSON5 via Parse Method

Clear and concise description of the problem

Hi Antony,

I came across this possible security issue regarding using lower than version 2.2.2 JSON5 library

@antfu/[email protected] requires json5@^1.0.1 via a transitive dependency on [email protected]

Problem:

The parse method of the JSON5 library before and including version 2.2.1 does not restrict parsing of keys named proto, allowing specially crafted strings to pollute the prototype of the resulting object.

This vulnerability pollutes the prototype of the object returned by JSON5.parse and not the global Object prototype, which is the commonly understood definition of Prototype Pollution. However, polluting the prototype of a single object can have significant security impact for an application if the object is later used in trusted operations.

Impact

This vulnerability could allow an attacker to set arbitrary and unexpected keys on the object returned from JSON5.parse. The actual impact will depend on how applications utilise the returned object and how they filter unwanted keys, but could include denial of service, cross-site scripting, elevation of privilege, and in extreme cases, remote code execution.

Suggested solution

Mitigation

This vulnerability is patched in json v2.2.2 and later.

Alternative

No response

Additional context

Details

Suppose a developer wants to allow users and admins to perform some risky operation, but they want to restrict what non-admins can do. To accomplish this, they accept a JSON blob from the user, parse it using JSON5.parse, confirm that the provided data does not set some sensitive keys, and then performs the risky operation using the validated data:


const doSomethingDangerous = (props) => {
  if (props.isAdmin) {
    console.log('Doing dangerous thing as admin.');
  } else {
    console.log('Doing dangerous thing as user.');
  }
};

const secCheckKeysSet = (obj, searchKeys) => {
  let searchKeyFound = false;
  Object.keys(obj).forEach((key) => {
    if (searchKeys.indexOf(key) > -1) {
      searchKeyFound = true;
    }
  });
  return searchKeyFound;
};

const props = JSON5.parse('{"foo": "bar"}');
if (!secCheckKeysSet(props, ['isAdmin', 'isMod'])) {
  doSomethingDangerous(props); // "Doing dangerous thing as user."
} else {
  throw new Error('Forbidden...');
}

If an attacker attempts to set the isAdmin key, their request will be rejected:

const props = JSON5.parse('{"foo": "bar", "isAdmin": true}');
if (!secCheckKeysSet(props, ['isAdmin', 'isMod'])) {
  doSomethingDangerous(props);
} else {
  throw new Error('Forbidden...'); // Error: Forbidden...
}

However, attackers can instead set the proto key to {"isAdmin": true}. JSON5 will parse this key and will set the isAdmin key on the prototype of the returned object, allowing the attacker to bypass the security check and run their request as an admin:

const props = JSON5.parse('{"foo": "bar", "__proto__": {"isAdmin": true}}');
if (!secCheckKeysSet(props, ['isAdmin', 'isMod'])) {
  doSomethingDangerous(props); // "Doing dangerous thing as admin."
} else {
  throw new Error('Forbidden...');
}

Validations

"eslint": ">=7.4.0" as peer dependency is not proper version

Describe the bug

When I use [email protected], I got error:

Oops! Something went wrong! :(

ESLint: 7.32.0

Error: Failed to load plugin 'unicorn' declared in '.eslintrc » @antfu/eslint-config » @antfu/eslint-config-vue » @antfu/eslint-config-ts » @antfu/eslint-config-basic': Cannot find module 'eslint/use-at-your-own-risk'

related issue: sindresorhus/eslint-plugin-unicorn#1544 (comment)

Reproduction

https://github.com/yunsii/antfu-eslint-config

System Info

System:
    OS: Linux 5.10 Ubuntu 20.04.4 LTS (Focal Fossa)
    CPU: (16) x64 AMD Ryzen 7 5700G with Radeon Graphics
    Memory: 14.13 GB / 19.55 GB
    Container: Yes
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 16.15.0 - ~/.nvm/versions/node/v16.15.0/bin/node
    Yarn: 1.22.18 - ~/.nvm/versions/node/v16.15.0/bin/yarn
    npm: 8.5.5 - ~/.nvm/versions/node/v16.15.0/bin/npm

Used Package Manager

pnpm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Protect against leaving `.only` in your tests

Clear and concise description of the problem

Sometimes when I write Vitest, Jest, Mocha, or Cypress tests, I commit .only describe or it blocks that I forgot about while developing.

This is bad because CI passes, but my test suites aren't running.

Suggested solution

Can we either extend or include something like https://www.npmjs.com/package/eslint-plugin-no-only-tests

Alternative

Projects do it themselves.

Additional context

No response

Validations

bug: asyncArrow can't be fixed

1654402571144

when i use eslint to fix in main package, the subpackage error can't be fixed.
I try to remove extends:"@antfu", fix worked.

Additionally, the same code in main package is not considered an error.

const a = async () => { return 1 } a() both in main and sub package (vitest module),the error just occur in sub package

Parsing error: expected trailing comma in .md file

Describe the bug

Inside a .md file I wrote :

<script setup>
const { data: images } = useFetch<ImageKit[]>('/api/imgkit')
</script>

which resulted in :
eslint bug

Reproduction

Please see Screenshot

System Info

------------------------------
- Operating System: `Darwin`
- Node Version:     `v18.12.1`
- Nuxt Version:     `3.0.0-rc.13`
- Nitro Version:    `0.6.1`
- Package Manager:  `[email protected]`
- Builder:          `vite`
- User Config:      `nitro`, `runtimeConfig`, `modules`, `alias`, `schemaOrg`, `image`, `colorMode`, `pwa`
- Runtime Modules:  `[email protected]`, `@kevinmarrec/[email protected]`, `@nuxt/[email protected]`, `@nuxtjs/[email protected]`, `@pinia/[email protected]`, `[email protected]`
- Build Modules:    `-`
------------------------------

Used Package Manager

npm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Rules of Hooks - React

Clear and concise description of the problem

Can a check for React hook rules be added? I have made a feature pull request. Please merge it if you can.

Suggested solution

Use eslint-plugin-react-hooks plugin.

Alternative

No response

Additional context

No response

Validations

Vue linting rules without TS

Clear and concise description of the problem

Is it possible for you to provide, linting rules for vue without TS rules?

Suggested solution

It requires removing 3-4 lines from the existing index.js file and related packages from package.json

Alternative

None

Additional context

No response

Validations

bug: no error when attribute can `undefined` because `arg?: <type>`

Hi antfu!,

I'm using your eslint configuration and it has a very serious error for me.
It appears that this configuration has disabled the ability to recognize a value that could be undefined when it is defined with ?:

Not working:
image

Working:
image

You can see that when I specify format?: string[] then eslint does not specify format as undefined and format.forEach is still valid. But when I specify the format?: string[] | void, the format.forEach will experience an error.

Please fix,
Thanks for read!

Enable `@typescript-eslint/no-floating-promises` and `@typescript-eslint/no-misused-promises`

Clear and concise description of the problem

It make sense to enable rules no-floating-promises and no-misused-promises. They can warn you not forget to await the async function. What why not enable them?

Suggested solution

Enable @typescript-eslint/no-floating-promises and @typescript-eslint/no-misused-promises.

Alternative

No response

Additional context

No response

Validations

how to make override work?

i am using vitesse, i want to override some rules in eslintrc but seems not working.

.eslintrc.js

module.exports = {
  extends: [
    '@antfu',
  ],
  rules: {
    'object-shorthand': ['never'],
  },
}

image

I tried this too but still not working

acdfvgfgbhg

fix auto error

Describe the bug

The plug -in is introduced and used, the vscode file is automatically fixed, and the file is saved after the file is modified

Reproduction

https://github.com/dbudaiya/dushenyan-utils

System Info

ESLint: Failed to load plugin '@typescript-eslint' declared in '.eslintrc.json » @antfu/eslint-config » @antfu/eslint-config-react » @antfu/eslint-config-ts': ENOENT: no such file or directory, open '/Users/dushenyan/Documents/openSource-code/dushenyan-utils/node_modules/.pnpm/@[email protected]_3bh5nkk7utn7e74vrwtv6rxmt4/node_modules/@typescript-eslint/eslint-plugin/dist/index.js' Referenced from: /Users/dushenyan/Documents/openSource-code/dushenyan-utils/node_modules/@antfu/eslint-config-ts/index.js. Please see the 'ESLint' output channel for details.

Used Package Manager

yarn

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Add type hints to the configuration

Clear and concise description of the problem

@antfu/eslint-config has become a part of my daily development specification customization reference, and I like some of its customized coding specifications!

This may be a little different. When I want to delve into the rules or principles of a library, I always like downloading its source code and reviewing it in the editor. But when I open the source code of this library to know the details of a specific rule, I always need to open the corresponding website and search for the corresponding rule name. It's a hassle for people who want to know what these rules disable/enable! I tried to find out if I could add hints to eslint config, so I found eslint-define-config, which has @antfu/eslint-config uses most of the prompt information and the corresponding link address in the external configuration, so can we also add it.

There should be some people who have the same needs as me, because eslint is a plug-in for code style, which varies from person to person. We always want to learn something from others to notice have yet to catch. Add type hints to this to make this even more convenient!

Suggested solution

Add type hints to the configuration, e.g. eslint-define-config.

Alternative

No response

Additional context

No response

Validations

vscode error

Describe the bug

Referenced from: /Users/mac/Desktop/Kfang/kfang-task-platform/node_modules/@antfu/eslint-config-vue/index.js
at configMissingError (/Users/mac/Desktop/Kfang/kfang-task-platform/node_modules/eslint/lib/cli-engine/config-array-factory.js:265:9)
at ConfigArrayFactory._loadExtendedPluginConfig (/Users/mac/Desktop/Kfang/kfang-task-platform/node_modules/eslint/lib/cli-engine/config-array-factory.js:792:31)
at ConfigArrayFactory._loadExtends (/Users/mac/Desktop/Kfang/kfang-task-platform/node_modules/eslint/lib/cli-engine/config-array-factory.js:725:29)
at ConfigArrayFactory._normalizeObjectConfigDataBody (/Users/mac/Desktop/Kfang/kfang-task-platform/node_modules/eslint/lib/cli-engine/config-array-factory.js:660:25)
at _normalizeObjectConfigDataBody.next ()
at ConfigArrayFactory._normalizeObjectConfigData (/Users/mac/Desktop/Kfang/kfang-task-platform/node_modules/eslint/lib/cli-engine/config-array-factory.js:596:20)
at _normalizeObjectConfigData.next ()
at ConfigArrayFactory._normalizeObjectConfigDataBody (/Users/mac/Desktop/Kfang/kfang-task-platform/node_modules/eslint/lib/cli-engine/config-array-factory.js:660:25)
at _normalizeObjectConfigDataBody.next ()
at ConfigArrayFactory._normalizeObjectConfigData (/Users/mac/Desktop/Kfang/kfang-task-platform/node_modules/eslint/lib/cli-engine/config-array-factory.js:596:20)
[Error - 7:52:04 PM] ESLint stack trace:
[Error - 7:52:04 PM] Error: Failed to load config "plugin:vue/vue3-recommended" to extend from.
Referenced from: /Users/mac/Desktop/Kfang/kfang-task-platform/node_modules/@antfu/eslint-config-vue/index.js

[Error - 7:52:04 PM] ESLint stack trace:
[Error - 7:52:04 PM] Error: Failed to load config "plugin:vue/vue3-recommended" to extend from.
Referenced from: /Users/mac/Desktop/Kfang/kfang-task-platform/node_modules/@antfu/eslint-config-vue/index.js

Reproduction

solve

System Info

macOs cataLina 10.15.6

Used Package Manager

yarn

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Cannot find module 'eslint-plugin-vue'

格式化vue文件的时候就会报错

image

packages.json
image
.eslintrc.js
image

,vscode.settings.json 工作区
image

Reproduction

System Info

-

Used Package Manager

pnpm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Conflict in VSCode between plugin:vue/vue3-recommended and @antfu/estlint-config-vue

I was trying to use Vitesse and my vscode shows a strange error like the image below:

image

I've opened the output, and shows this message:

image

This message appears in every typing I made. I was looking to fix it, and I'm discover that if I comment the line 17 of the @antfu/eslint-config-vue/index.js, the errors disapear in my screen, like the image below:

image

I think this could be a problem in eslint itself, but I come here first just to see if you made something magic, like Vitesse (I really like Vitesse).

Please upgrade typescript-eslint to support Typescript 4.8

Clear and concise description of the problem

In TypeScript versions greater than 4.8, using "eslint . --fix", there will be

WARNING: You are currently running a version of TypeScript which is not officially supported by @typescript-eslint/typescript-estree.

You may find that it works just fine, or you may not.

SUPPORTED TYPESCRIPT VERSIONS: >=3.3.1 <4.8.0

YOUR TYPESCRIPT VERSION: 4.8.2

Please only submit bug reports when using the officially supported version.

typescript-eslint in 5.36.0 added support for typescript4.8, please upgrade the relevant dependencies

Suggested solution

I guess it can be upgraded to depend on

Alternative

No response

Additional context

No response

Validations

These json rules seems not works

If want to change default behaivior, these rules should be add prefix jsonc, likes package.json rules

'jsonc/comma-dangle': ['error', 'never'],

{
files: ['*.json', '*.json5'],
parser: 'jsonc-eslint-parser',
rules: {
'quotes': ['error', 'double'],
'quote-props': ['error', 'always'],
'comma-dangle': ['error', 'never'],
},
},

image

image

The indentation line looks weird

Describe the bug

image

I set 4 spaces as an indent, but his indent line didn't follow, I'm not sure what triggered this

Reproduction

module.exports = { extends: '@antfu', rules: { '@typescript-eslint/no-use-before-define': 'off', '@typescript-eslint/prefer-ts-expect-error': 'off', '@typescript-eslint/ban-ts-comment': 'off', 'no-console': 'off', 'vue/html-indent': ['error', 4], '@typescript-eslint/semi': ['error', 'always'], '@typescript-eslint/indent': ['error', 4], 'indent': ['error', 4], 'semi': ['error', 'always'], 'prefer-promise-reject-errors': 'off', 'no-debugger': 'warn', 'no-restricted-syntax': 'off', '@typescript-eslint/brace-style': ['error', '1tbs'], }, };

System Info

System:
    OS: Windows 10
    CPU: (20) x64 12th Gen Intel(R) Core(TM) i7-12700K
    Memory: 16.40 GB / 31.34 GB
  Binaries:
    Node: 14.19.0 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.19 - f:\SDK_ALL\Yarn\bin\yarn.CMD
    npm: 6.14.16 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: 44.22621.601.0
    Internet Explorer: 11.0.22621.1

Used Package Manager

yarn

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Add JSON-related configuration in the README file

Hi! 👋

In order to automatically format json and jsonc files, I had to add them to the eslint.validate option in the settings.json file (in addition to the other options). So, if you find it relevant, I think this setting could also be added in the README file, more precisely in the Config VS Code auto fix section as a link to this page or based on the snippet below:

{
  "eslint.validate": ["javascript", "javascriptreact", "json", "jsonc"]
}

What do you think? If it makes sense, let me know if I can help! 😄

References:

why put eslint plugin/config into `dependencies`?

I am looking through pnpm source code recently and find out the author put eslint relative thing into dependenciesas an eslint-config package. Then I check this repo, same with pnpm eslint-config

it's really confusing me because it against my acknowledge w/ dependencies, it's more reasonable for me to put the lint\build\transpiler tool into devDependencies

and I have already tested locallly, it still works when you put them into devDependencies, so I can't help opening a ticket,
as far I know, I prefer @ljhard's answer, so I want to hear from you, what do you think?

Script setup and normal script `inheritAttrs`

https://vuejs.org/api/sfc-script-setup.html#usage-alongside-normal-script

'vue/component-tags-order': ['error', {
    order: ['script', 'template', 'style'],
}],
/**
 * @type {import('eslint').Linter.Config}
 */
module.exports = {
  extends: '@antfu',
  ignorePatterns: '*.json',
   rules: {
    '@typescript-eslint/no-unused-vars': 'off',
    'vue/component-tags-order': ['error', {
      order: ['script:not([setup])', 'script[setup]', 'template', 'style'],
    }],
}

with your config and overridden config still getting error, and eslint fix move normal script content into script setup

<script></script>

<script setup>
	
	export default {
		inheritAttrs: false
	}
</script>

Update to typescript 4.5

Hi @antfu

amazing work, just a small request, could you update Typescript to 4.5 and with this maybe @typescript-eslint/eslint-plugin since i'm currently getting the following message when I start a project:

WARNING: You are currently running a version of TypeScript which is not officially supported by @typescript-eslint/typescript-estree.

You may find that it works just fine, or you may not.

SUPPORTED TYPESCRIPT VERSIONS: >=3.3.1 <4.5.0

YOUR TYPESCRIPT VERSION: 4.5.2

Please only submit bug reports when using the officially supported version.

Conflict with `@nuxt/content` v2

This package and @nuxt/content v2 both depend on different versions of mdast-util-from-markdown. When both of these packages are added to a Nuxt 3 project (via Yarn), the following error occurs (on nuxi dev).

 ERROR  [worker reload] [worker init] Named export 'parseEntities' not found. The requested module 'file:///.../website/node_modules/parse-entities/index.js' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from 'file:///.../website/node_modules/parse-entities/index.js';
const { parseEntities } = pkg;


  import { parseEntities } from 'node_modules/parse-entities/index.js';
  ^^^^^^^^^^^^^
  SyntaxError: Named export 'parseEntities' not found. The requested module 'node_modules/parse-entities/index.js' is a CommonJS module, which may not support all module.exports as named exports.
  CommonJS modules can always be imported via the default export, for example using:

  import pkg from 'node_modules/parse-entities/index.js';
  const { parseEntities } = pkg;

  at ModuleJob._instantiate (node:internal/modules/esm/module_job:127:21)
  at async ModuleJob.run (node:internal/modules/esm/module_job:193:5)
  at async Promise.all (index 0)
  at async ESMLoader.import (node:internal/modules/esm/loader:337:24)
  at async loadESM (node:internal/process/esm_loader:88:5)
  at async handleMainPromise (node:internal/modules/run_main:61:12)

This is happening because @nuxt/content relies on the newer ESM-only version of mdast-util-from-markdown, while this package (through eslint-plugin-markdown) relies on the older CJS-only version of mdast-util-from-markdown. When both of these packages are added to a project, only one of these dependency versions is being resolved.

eslint不会自动修复单行过长的问题

我现在正在习惯仅使用eslint格式化代码,但现在有个不太舒服的点是我限制了单行最大长度,但eslint不会帮我自动折行,Anthony宝贝有没有什么替代方案,爱你~

"rules": {
    "max-len": [
      "error",
      {
        "code": 80
      }
    ]
}

fix: Unnecessary { after 'if' condition.

Describe the bug

image

auto format

// 月
    if (now.getFullYear() === old.getFullYear() && now.getMonth() === old.getMonth()) {
      h[month]++
    }
    else
      h[month] = 1

    // 周
    const weekStart = dayjs().startOf('week').valueOf()
    const weekEnd = dayjs().endOf('week').valueOf()
    if (last >= weekStart && last <= weekEnd) {
      h[week]++
    }
    else
      h[week] = 1

    // 日
    if (now.getFullYear() === old.getFullYear() && now.getMonth() === old.getMonth() && now.getDate() === old.getDate()) {
      h[day]++
    }
    else
      h[day] = 1

modify to:

// 月
    if (now.getFullYear() === old.getFullYear() && now.getMonth() === old.getMonth())
      h[month]++
    else h[month] = 1

    // 周
    const weekStart = dayjs().startOf('week').valueOf()
    const weekEnd = dayjs().endOf('week').valueOf()
    if (last >= weekStart && last <= weekEnd)
      h[week]++
    else h[week] = 1

    // 日
    if (now.getFullYear() === old.getFullYear() && now.getMonth() === old.getMonth() && now.getDate() === old.getDate())
      h[day]++
    else h[day] = 1

no warning

Reproduction

System Info

System:
    OS: macOS 12.6.1
    CPU: (12) x64 Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz
    Memory: 394.57 MB / 16.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 18.12.1 - ~/.nvm/versions/node/v18.12.1/bin/node
    Yarn: 1.22.19 - ~/.nvm/versions/node/v18.12.1/bin/yarn
    npm: 8.19.2 - ~/.nvm/versions/node/v18.12.1/bin/npm
  Browsers:
    Chrome: 107.0.5304.110
    Safari: 16.1

Used Package Manager

pnpm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Peer dependency warning: TypeScript

Describe the bug

I used @antfu/eslint-config package in my Vue 3 project that I don't use TypeScript. When I installed the package, I got a peer dependency warning. It told me that I should install TypeScript as a dev dependency, which I don't want to do (for now).

Reproduction

Create a new Vue 3 project (possibly with Vite) without TypeScript. Then, install @antfu/eslint-config package (with pnpm). When installing the dependency, you'll receive a peer dependency warning related to TypeScript.

System Info

System:
    OS: macOS 12.5
    CPU: (10) arm64 Apple M1 Pro
    Memory: 114.16 MB / 16.00 GB
    Shell: 5.8.1 - /bin/zsh
Binaries:
    Node: 16.16.0 - ~/.nvm/versions/node/v16.16.0/bin/node
    Yarn: 1.22.19 - ~/.yarn/bin/yarn
    pnpm: 7.8.0 - ~/Library/pnpm/pnpm
    npm: 8.11.0 - ~/.nvm/versions/node/v16.16.0/bin/npm
    Watchman: 2022.07.04.00 - /opt/homebrew/bin/watchman
Browsers:
    Firefox Developer Edition: 104.0
    Safari: 15.6

Used Package Manager

pnpm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

基于 @antfu 二次封装 Shareable 库,提示 Error: Failed to load plugin 'import' declared in 'clean-webpack-plugin/.eslintrc.cjs » @shilong/eslint-config/lib/base.js » @antfu/eslint-config-basic': Cannot find module 'eslint-plugin-import'

Describe the bug

基于 @antfu 二次封装 Shareable 库,提示 Error:
Failed to load plugin 'import' declared in 'clean-webpack-plugin/.eslintrc.cjs » @shilong/eslint-config/lib/base.js » @antfu/eslint-config-basic': Cannot find module 'eslint-plugin-import'.

应该不是bug. 但是希望求助下大神如何解决这类问题;

Reproduction

https://github.com/Onlylonger/eslint/tree/new

System Info

在 clean-webpack-plugin 目录里面。
npx eslint .

Used Package Manager

npm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

How to use with Astro Components?

Hi There,

First of all, thanks a lot for providing this set of rules; it's been really helpful to me in the past when working wie Vue3.
I just started playing around with https://astro.build/ and would like to use the @antfu/eslint-config-ts rules in *.astro components. Could you provide me with some advice on how to add the filetype?

This is my current config:

eslintrc

{
  "extends": [
    "@antfu/eslint-config-ts",
    "plugin:tailwindcss/recommended",
    "plugin:astro/recommended",
    "plugin:astro/jsx-a11y-strict",
  ],
  "plugins": [
    "tailwindcss",
    "jsx-a11y",
  ],
  "rules": {
    "no-console": "warn",
    "tailwindcss/no-custom-classname": "warn",
    "antfu/if-newline": "error",
  },
  "overrides": [
    {
      "files": ["*.astro"],
      "parser": "astro-eslint-parser",
      "parserOptions": {
        "parser": "@typescript-eslint/parser",
        "extraFileExtensions": [".astro"],
      },
      "rules": {
      },
    },
  ],
}

Many thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.