Я использую eslint в визуальном коде для форматирования файлов js, но он выдает ошибки каждый раз, когда я запускаю его, вот моя командная строка для его запуска
node ./node_modules/eslint/bin/eslint -- src --fix сообщение об ошибке
E:\PATH\src\reducers\roote-reducer.js
1:8 error There should be no space after '{' object-curly-spacing
1:26 error There should be no space before '}' object-curly-spacing
6:1 error Expected indentation of 1 tab but found 2 spaces indent
7:1 error Expected indentation of 1 tab but found 2 spaces indent
8:4 error Newline required at end of file but not found eol-last
E:\PATH\src\reducers\schedule-reducer.js
1:8 error There should be no space after '{' object-curly-spacing
1:22 error There should be no space before '}' object-curly-spacing
4:1 error Expected indentation of 1 tab but found 4 spaces indent
7:24 error Missing space before function parentheses space-before-function-paren
7:54 error Missing space before opening brace space-before-blocks
8:1 error Expected indentation of 1 tab but found 4 spaces indent
9:1 error Expected indentation of 1 tab but found 4 spaces indent
E:\PATH\src\register-service-worker.js
12:1 error Expected indentation of 1 tab but found 2 spaces indent
17:1 error Expected indentation of 5 tabs but found 6 spaces indent
17:7 error Use regex shorthands to improve readability unicorn/regex-shorthand
22:1 error Expected indentation of 1 tab but found 2 spaces indent
✖ 309 problems (309 errors, 0 warnings)
309 errors, 0 warnings potentially fixable with the `--fix` option.
Как я могу их исправить автоматически?
Как исправить эти ошибки / предупреждения?



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Чтобы использовать опцию --fix, вам нужно запустить eslint напрямую.
Попробуй это
./node_modules/.bin/eslint src --fix
В Windows:
.\node_modules\.bin\eslint src\** --fix
работает некорректно, выдает всего одну ошибку (первую ошибку) и не решает ее!
Отредактировал, можете подробнее рассказать о проблеме?
Пожалуйста, попытайтесь немного объяснить свое решение, чтобы люди могли понять, почему возникает проблема, и в чем заключается настоящая проблема и решение.
Это сработало для меня после того, как я указал каталог в качестве последнего аргумента после --fix, например: ./node_modules/.bin/eslint --fix myJsFiles/. Спасибо
Нет необходимости запускать двоичные файлы прямо с ./node_modules/.bin. Для этого предназначены npx и npm exec.
Формат должен быть:
./node_modules/.bin/eslint --fix path/to/file.js
См. эта ветка (и ответ aravind1078) для получения дополнительной информации.
Я использовал ./node_modules/.bin/eslint --fix src /**.* для запуска для всех файлов внутри / src
Если это не так
extend(config, ctx) {
// Run ESLint on save
if (ctx.isDev && ctx.isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/,
options: {
fix: true
}
})
}
}
You. You can use this on the first page
const colors = require('vuetify/es5/util/colors').default
const pkg = require('./package')
require('dotenv').config()
module.exports = {
mode: 'universal',
/*
** Headers of the page
*/
head: {
titleTemplate: '%s - ' + process.env.npm_package_name,
title: process.env.npm_package_name || '',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{
hid: 'description',
name: 'description',
content: process.env.npm_package_description || ''
}
],
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }]
},
/*
** Customize the progress-bar color
*/
loading: { color: '#fff' },
/*
** Global CSS
*/
css: [],
/*
** Plugins to load before mounting the App
*/
plugins: [],
/*
** Nuxt.js dev-modules
*/
buildModules: [
// Doc: https://github.com/nuxt-community/eslint-module
'@nuxtjs/eslint-module',
'@nuxtjs/vuetify'
],
/*
** Nuxt.js modules
*/
modules: [
// Doc: https://axios.nuxtjs.org/usage
'@nuxtjs/axios',
'@nuxtjs/pwa',
// Doc: https://github.com/nuxt-community/dotenv-module
'@nuxtjs/dotenv'
],
/*
** Axios module configuration
** See https://axios.nuxtjs.org/options
*/
axios: {},
/*
** vuetify module configuration
** https://github.com/nuxt-community/vuetify-module
*/
/*
** Build configuration
*/
build: {
extend(config, ctx) {
// Run ESLint on save
if (ctx.isDev && ctx.isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/,
options: {
fix: true
}
})
}
}
}
}Это устранило проблему в моем проекте Nuxt, большое спасибо
Попробуй бежать
eslint --fix
вам нужно сначала установить eslint
npm install -g eslint
Спасибо. Это тоже решило мою проблему. Встретился с этим и попытался отладить почти 1 час
Герой! Могу я добавить использование . в конце. Огромное спасибо!
У меня была та же проблема, что и я
eslint --fix fileName.extention
Выполните следующую команду в новом терминале:
./node_modules/.bin/eslint --fix . --ext .js,.vue src
Спасибо, это сработало
Пакет первой установки: npm install -g eslint
а также
Запустить: eslint --fix
Сначала установите eslint, если вы еще этого не сделали
npm install -g eslint
Тогда беги
eslint --fix path/to/file.extension
Note: You will have to run the the above command every time after making changes to that particular file.
в каталоге, в котором существует код, запустите:
eslint --fix .
вместо
eslint --fix
поскольку команде нужен аргумент, который указывает каталог, в котором существует код, или сам файл, к которому вы хотите применить линтинг
Используйте Терминал командной строки, чтобы выполнить приведенные ниже команды в Visual Studio Code.
Убедитесь, что файл .eslintrc.yml настроен для рабочего проекта.
Чтобы исправить проблемы с ворсом в файле
npx eslint file1.js --fix
Чтобы исправить проблемы с ворсом во всех файлах в папке
npx eslint ./folder_name --fix
По какой-то причине это было единственное решение, которое сработало для меня ... большое спасибо!
--fix, когда я использую eslint-config-airbnb-base вместо @ nuxtjs / eslint-модуль в проекте Nuxt.js./node_modules/.bin/eslint --fix
Однако я предпочитаю написать еще два скрипта в package.json.
"lint": "eslint --ext \".js,.vue\" --ignore-path .gitignore .", "lint-fix": "npm run lint -- --fix"
И запустите yarn lint-fix или npm run lint-fix
Обратите внимание, что не все ошибки / предупреждения можно исправить с помощью
--fix.