The problem
Nuxt.js is my go to framework for static site generation. I was getting a vue/comment-directive
error on bootstrap and wasn’t able to get pass this error screen.
Installing Nuxt.js
First, let’s make sure we have all the prerequisites installed.
I used create-nuxt-app
to bootstrap my Nuxt project.
npm i create-nuxt-app
Creating a Nuxt project
Once you have create-nuxt-app
installed, we can create the app by running the nuxt-app
command.
npm init nuxt-app <project-name>
The command creates a project directory with the folder structure necessary to start building a Nuxt app.
Let’s start the app.
npm run dev
The error
As soon as I saw the error in my terminal, I googled vue/comment-directive
and saw the rule being included in all of the eslint plugins.
Module Error (from ./node_modules/eslint-loader/dist/cjs.js): friendly-errors 15:25:13
/Users/michaelle/Developer/personal/michael1e.com/client/pages/index.vue
25:12 error clear vue/comment-directive
The rule allows us to have eslint-disable
functionality in our Vue <template>
. The rule is throwing false positives, and we need to turn it off in our .eslintrc.js
file.
Adding a custom rule in .eslintrc.js
Open the .eslintrc.js
file in your root directory.
We can add a custom rule to turn off vue/comment-directive
.
module.exports = {
root: true,
env: {
browser: true,
node: true
},
parserOptions: {
parser: 'babel-eslint'
},
extends: [
'@nuxtjs',
'prettier',
'prettier/vue',
'plugin:prettier/recommended',
'plugin:nuxt/recommended'
],
plugins: [
'prettier'
],
// add your custom rules here
rules: {
'nuxt/no-cjs-in-config': 'off',
'vue/comment-directive': 'off'
}
}
I’m able to rerun the app without the eslint errors.
Содержание
- Nuxt supress vue/comment-directive error
- The problem
- Installing Nuxt.js
- Creating a Nuxt project
- Fixing the Nuxt vue/comment-directive error
- The error
- Adding a custom rule in .eslintrc.js
- Плагин ESLint Vue, показывающий ложные срабатывания для директивы vue / comment
- Official ESLint plugin for Vue.js
- Related tags
- Wrong detect of `Parsing error: invalid-first-character-of-tag-name` in expression.
- Style Guide Collaboration
- Supports for Vue.js 3.x
- Error Clear Vue Comment Directive Best Recipes
- Recently Recipes
The problem
Nuxt.js is my go to framework for static site generation. I was getting a vue/comment-directive error on bootstrap and wasn’t able to get pass this error screen.
Nuxt vue/comment-directive error
Installing Nuxt.js
First, let’s make sure we have all the prerequisites installed.
I used create-nuxt-app to bootstrap my Nuxt project.
Creating a Nuxt project
Once you have create-nuxt-app installed, we can create the app by running the nuxt-app command.
The command creates a project directory with the folder structure necessary to start building a Nuxt app.
Let’s start the app.
The error
As soon as I saw the error in my terminal, I googled vue/comment-directive and saw the rule being included in all of the eslint plugins.
vue/comment-directive error in terminal
The rule allows us to have eslint-disable functionality in our Vue . The rule is throwing false positives, and we need to turn it off in our .eslintrc.js file.
Adding a custom rule in .eslintrc.js
Open the .eslintrc.js file in your root directory.
nuxt eslintrc file
We can add a custom rule to turn off vue/comment-directive .
turning off vue/comment-directive
I’m able to rerun the app without the eslint errors.
Источник
Плагин ESLint Vue, показывающий ложные срабатывания для директивы vue / comment
Насколько я понимаю, после перехода с VueCLI на Vite я должен выполнить линтинг «вручную»; поправьте меня если я ошибаюсь. Поскольку я хочу только линтовать свои файлы .ts и .html (я разделяю их даже для компонентов), у меня есть этот скрипт в моем пакете json:
«lint»: «eslint —ext .ts —ext .html src/»
Он обнаружил некоторые проблемы, такие как отсутствие :key циклов, но он также показывает мне эту ошибку для каждого шаблона:
И это всегда закрывающий тег любых корневых элементов в моем template.html. Если есть только один корневой элемент, я получаю одно предупреждение для файла, если есть несколько корневых элементов, я получаю предупреждение для каждого закрывающего тега.
Я не понимаю, на что жалуется это правило, поскольку, согласно его документации , оно есть для комментариев eslint-disable, которых у меня нет в моих шаблонах.
У меня была такая же проблема, но в nuxt с eslint мне просто нужно было обновить eslint-config и eslint-module:
Я только что обновил свои зависимости npm, и у меня такая же ошибка.
Я читал документацию eslint и, наконец, понял, что вы можете удалить, false error если настроите правило в .eslintrc.js файле конфигурации.
это мой .eslintrc.js файл конфигурации:
добавить правило «vue/comment-directive»: 0 и то !, сообщение об ошибке удалено !.
- 0 означает disabled
- 1 означает warning
- 2 означает error
Попробуйте изменить его в своей IDE на то, как оно работает
(В моем случае мне приходилось останавливать сервер и повторно запускать его каждый раз, когда я менял значение в этом файле конфигурации.)
Установите этот фрагмент на .eslintrc.js
Решите мою проблему, мне интересно, почему. Решение из документации
Это своего рода временное исправление, которое сработало для меня, и я думаю, что оно сработает и для вас.
Это правило включено во все «plugin: vue / base», «plugin: vue / essential», «plugin: vue / vue3-essential», «plugin: vue / настоятельно рекомендуется», «plugin: vue / vue3- настоятельно рекомендуется »,« плагин: vue / рекомендуется »и« плагин: vue / vue3-рекомендуется ».
ESLint не предоставляет API для улучшения функциональности eslint-disable, а правила ESLint не могут влиять на другие правила. Но ESLint предоставляет API процессоров.
Это правило отправляет все комментарии, похожие на eslint-disable, как ошибки в пост-процесс обработчика файлов .vue, затем пост-процесс удаляет все ошибки директивы vue / comment и сообщения об ошибках в отключенных областях.
Все, что вам нужно сделать, это добавить eslint-disable-next-line vue / component-tags-order эту строку как комментарий выше везде, где вы используете комментарии внутри тегов в каждом блоке, который необходимо указать, добавляются ли комментарии.
Источник
Official ESLint plugin for Vue.js
Overview
Official ESLint plugin for Vue.js
Contribution is welcome!
Working with Rules
Before you start writing a new rule, please read the official ESLint guide.
Next, in order to get an idea how does the AST of the code that you want to check looks like, use the astexplorer.net. The astexplorer.net is a great tool to inspect ASTs, also Vue templates are supported.
After opening astexplorer.net, select Vue as the syntax and vue-eslint-parser as the parser.
Since single file components in Vue are not plain JavaScript, the default parser couldn’t be used, so a new one was introduced. vue-eslint-parser generates enhanced AST with nodes that represent specific parts of the template syntax, as well as what’s inside the
Comments
Wrong detect of `Parsing error: invalid-first-character-of-tag-name` in expression.
Tell us about your environment
- ESLint Version:
- eslint-plugin-vue Version:
Please show your full configuration:
What did you do? Please include the actual source code causing the issue.
What did you expect to happen?
What actually happened? Please include the actual, raw output from ESLint.
Style Guide Collaboration
I’m developing an official Vue style guide and although not all rules there will be enforceable through this plugin, I think it makes sense to collaborate here, especially for those rules that are enforceable. Right now, I’m thinking the style guide could serve as the official documentation for any recommended rules in this plugin and these two resources could be published together.
You can see the current progress in this branch, with the live result here. Any feedback/contributions are welcome and rules are not set in stone, so don’t panic if you see something you disagree with. 😄
I’ve also not kept up-to-date with the conversation in various issues here, so I apologize if some of it is out of sync with plans you’ve been making. Please ping me on discussions you think I should know about, or if you’d like my input.
Supports for Vue.js 3.x
In this issue, I will list the Vue.js 3.x changes that need to be supported by eslint-plugin-vue .
- [x] Support for Fragments. Plans for the Next Iteration of Vue.js
- [x] #1038 Change vue/valid-template-root to allow multiple root nodes.
- [x] #1038 Add vue/no-multiple-template-root rule that disallows multiple root nodes (for Vue 2).
- [x] Removing v-bind ‘s .sync modifier and replacing it with an argument on v-model . RFC0005
- [x] #1039 Change vue/valid-v-model to allows argument (component only).
- [x] #1039 Add vue/no-v-model-argument rule that disallows argument (for Vue 2).
- [x] #1039 Add vue/no-deprecated-v-bind-sync rule that disallows v-bind.sync .
- [x] Functional API Change. RFC0007
- [x] #1119 Add vue/no-deprecated-functional-template rule that disallows .
- [x] Global API changes. RFC0009
- [x] #1073 Add the CallExpression of app.component and app.mixin to utils/index.isVueComponent .
- [x] v-model API changes RFC0011
- [x] #1039 Modify vue/valid-v-model rule to provide support for custom modifiers. https://github.com/vuejs/eslint-plugin-vue/issues/1035#issuecomment-578446775
- [x] #1039 Add vue/no-custom-modifiers-on-v-model rule to checks if v-model does not contain custom modifiers (Vue 2 backward compatibility) https://github.com/vuejs/eslint-plugin-vue/issues/1035#issuecomment-578446775
- [ ] Composition API. RFC0013
- [ ] Add the setting of the setup property to vue/order-in-components rule.
- [x] #1065 Add vue/no-ref-as-operand rule. https://github.com/vuejs/eslint-plugin-vue/issues/1035#issuecomment-575315812
- [x] #1068 Add vue/no-watch-after-await rule. https://github.com/vuejs/eslint-plugin-vue/issues/1035#issuecomment-575315812
- [x] #1067 Add vue/no-lifecycle-after-await rule. https://github.com/vuejs/eslint-plugin-vue/issues/1035#issuecomment-575315812
- [x] #1066 Add vue/no-setup-props-destructure rule. https://github.com/vuejs/eslint-plugin-vue/issues/1035#issuecomment-575315812
- [x] #1082 Change vue/no-dupe-keys rule and vue/no-reserved-keys to handle setup .
- [x] Drop support for using numbers (keyCodes) as v-on modifiers. RFC0014
- [x] #1079 Add vue/no-deprecated-v-on-number-modifiers rule that disallows numbers as v-on modifiers.
- [x] #1118 Add vue/no-deprecated-vue-config-keycodes rule that disallows Vue.config.keyCodes .
- [x] Remove support for filters. RFC0015
- [x] #1043 Add vue/no-deprecated-filter rule that disallows Vue2 filter.
- [x] Remove inline-template . RFC0016
- [x] #1100 Add vue/no-deprecated-inline-template rule that disallow inline-template attributtes.
- [x] Using as component’s root will no longer trigger transitions when the component is toggled from the outside.. RFC0017
- [x] #1099 Add vue/require-v-if-inside-transition rule that checks whether expose a boolean prop to control the presence of content inside . e.g v-if , v-show . https://github.com/vuejs/eslint-plugin-vue/issues/1035#issuecomment-575229114
- [x] Removing object declaration for data RFC0019
- [x] #1083 Add vue/no-deprecated-data-object-declaration rule
- [x] Remove $on , $off and $once instance methods RFC0020
- [x] #1097 Add vue/no-deprecated-events-api rule
- [x] Custom Elements Interop Improvements RFC0027
- [x] #1117 Add vue/no-deprecated-html-element-is rule that disallow the is attribute on HTML elements.
- [ ] «emits» component option RFC0030
- [ ] Add the setting of the emits property to vue/order-in-components rule.
- [x] #1124 Add vue/require-explicit-emits rule that requires the emits option to have a name called by $emit() .
- [x] #1129 Add vue/return-in-emits-validator rule enforces that a return statement is present in emits validator.
- [x] Attribute Fallthrough Updates.RFC0031
- [x] #1130 Add vue/no-deprecated-v-on-native-modifier rule that disallow .native modifier on v-on .
- [x] #1133 Add vue/no-deprecated-dollar-listeners-api rule that disallow $listeners .
- TODO I need to check if any RFCs after RFC0033 are added.
List the changes after #1036 was merged.
- [x] Add categories for Vue 3
- [x] essential for Vue 3
- [x] Add vue/no-deprecated-filter rule.
- [x] Add vue/no-deprecated-v-bind-sync rule.
- [x] #1079 Add vue/no-deprecated-v-on-number-modifiers rule.
- [x] #1083 Add vue/no-deprecated-data-object-declaration rule
- [x] #1097 Add vue/no-deprecated-events-api rule
- [x] #1100 Add vue/no-deprecated-inline-template rule
- [x] #1099 Add vue/require-v-if-inside-transition rule.
- [x] Add vue/no-ref-as-operand rule.
- [x] #1068 Add vue/no-watch-after-await rule.
- [x] Add vue/no-lifecycle-after-await rule.
- [x] Add vue/no-setup-props-destructure rule.
- [x] #1061 Add vue/no-deprecated-scope-attribute rule.
- [x] #1061 Add vue/no-deprecated-slot-attribute rule.
- [x] #1061 Add vue/no-deprecated-slot-scope-attribute rule.
- [x] Remove vue/valid-v-bind-sync rule.
- [x] #1119 Add vue/no-deprecated-functional-template rule.
- [x] #1117 Add vue/no-deprecated-html-element-is rule.
- [x] #1118 Add vue/no-deprecated-vue-config-keycodes rule.
- [x] #1130 Add vue/no-deprecated-v-on-native-modifier rule.
- [x] #1133 Add vue/no-deprecated-dollar-listeners rule.
- [x] #1129 Add vue/return-in-emits-validator rule.
- [x] strongly-recommended for Vue 3
- [x] recommended for Vue 3
- [x] essential for Vue 3
- [x] Change categories for Vue 2
- [x] essential for Vue 2
- [x] Add vue/no-multiple-template-root rule.
- [x] Add vue/no-v-model-argument rule.
- [x] Add vue/no-custom-modifiers-on-v-model rule.
- [x] strongly-recommended for Vue 2
- [x] recommended for Vue 2
- [x] essential for Vue 2
Источник
Recently Recipes
Cute chocolate «cauldrons» hold a cool, creamy orange-flavored yogurt in this recipe. The unfilled cups.
Provided by Taste of Home
Provided by Catherine McCord
This is my technique for veal demi-glace, and there’s not much to it. I’m going for a pure veal stock.
Provided by Chef John
OMG. I had to make this cake this past Sunday for my Mary Kay party.. It was a huge hit. It was also.
Provided by vicky hunt
Good food doesn’t always have to cost a fortune! Your family will love this. Full of flavor and easy.
Provided by Melissa Baldan
This is a very good potato dish , I stem baby red potatoes and smother them in real butter and parsley.
Provided by Karla Everett
Provided by á-174942
Try this Instant Pot®-friendly variation of a traditional bean stew from the Portuguese region of Azores.
Provided by Ryan C Mathews
Provided by Florence Fabricant
A unique twist on a classic white chocolate fudge recipe! While quick and easy to prepare, Bruce’s®.
Provided by Bruce’s Yams
Sure you can make a quick Chicken Pot Pie using already made pie crust, canned soups, vegetables and.
Provided by Julia Ferguson
This delicious red velvet pound cake is the perfect combination of flavors. Make sure the cake has cooled.
Provided by Taste of Home
Dis is da toe curlin Texicajun hybrid of a classic dish. This will put a smile on everyone’s face that’s.
Provided by Lupe Boudreaux
Provided by Kemp Minifie
This is a tender and delicious baked pork chop recipe, with an Italian flair.
Источник
4erkashin opened this issue 2 years ago · comments
Checklist
- I have tried restarting my IDE and the issue persists.
- I have read the FAQ and my problem is not listed.
Tell us about your environment
- ESLint version: 6.8.0
- eslint-plugin-vue version: 7.0.0-0
- Node version: 12.14.1
- Operating System: Ubuntu 20.04.1 LTS
Please show your full configuration:
module.exports = { root: true, env: { node: true }, extends: ['plugin:vue/vue3-essential', 'eslint:recommended', '@vue/prettier'], parser: 'vue-eslint-parser', parserOptions: { parser: 'babel-eslint' }, rules: { 'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off', 'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off' } };
What did you do?
Just created project with vue create
What did you expect to happen?
No linting errors
What actually happened?
error: clear (vue/comment-directive) at public/index.html:21:8:
19 | <!-- built files will be auto injected -->
20 | </body>
> 21 | </html>
| ^
22 |
Same here.
Only solution for me was to disable the rule
rules: {
'vue/comment-directive': 'off'
}
@vanderb yeah. Did the same too. But it looks like a kludge.
You should at least use an override specific to html files for now since you probably still want that rule in vue files:
{
// HACK: https://github.com/vuejs/eslint-plugin-vue/issues/1355
files: ['**/*.html'],
rules: { 'vue/comment-directive': 'off' },
},
@ota-meshi I really don’t know should I use it for .html
or not. Unfortunately, I’m not so well experienced yet.
But I scaffolded app from CLI and wish there weren’t errors. So, could you please explain me, how to configure ESLint correctly? Is it enough to use override from your answer or there is something else I should know?
@ota-meshi The problem seems to be caused by the rule being applied to plain html files. If you look at the OP, you’ll see that it mentions the public/index.html
file as causing the issue. This rule only make sense in the context of a vue file anyway, so turning it off for html files, for which it shouldn’t have been enabled in the first place, make sense.
I am not saying we should enable it for html files. I am saying it IS enabled out of the box for them and shouldn’t.
Adding the override I mentioned as is fixes the issue while keeping the rule enabled for vue files, as opposed to @vanderb ‘s suggestion which disables it outright.
ESLint does not lint .html
by default. Why do you lint .html
with ESLint?
If you don’t need to apply ESLint to .html
, I think you should exclude .html
. I think you’re probably targeting .html
somewhere in the settings.
I don’t understand English, so I may not understand what you are saying correctly.
I think I know what is going on.
@4erkashin Are you using WebStorm?
I noticed that when creating a new project with npx @vue/cli create foobar
and then running npm run lint
, everything is good.
If I open the public/index.html
file in WebStorm, I get the ESLint error in the IDE. I think it might be WebStorm trying to lint every file you open even if you don’t have an explicit parser configured for them.
I still don’t know why vue/comment-directive
triggers in this case since it should be bound to **/*.vue
.
@kawazoe yeah I’m using webstorm. Got it, thanks for explanation)
Should I close the issue? Looks like jetbrains related only.
It’s probably a JetBrains issue.
My workaround will still work for you if you want to use it while we wait for a fix from them.
If you report it in their tracker, can you link it here so I can follow over there as well?
@4erkashin it indeed looks like WebStorm issue. We are going to fix it on our side, you can close the issue.
I have this issue on a fresh vue cli install, Using Visual studio code… So I don’t think it is explicitly to do with webstorm.
I have also added the rule:
"vue/comment-directive": 0
And the issue still persists.
@Tricky-Ricky do you get the issue when invoking from command line? If not, than it’s most likely a problem in VSCode integration.
The issue is with the linter configuration in the Vue install.
I did a fresh install without the linter, wrote the same code with no errors, and it displayed fine.
Tried again with the linter installed on a fresh install, same error…
This is with @vue/cli 4.5.11
Choosing vue 2 with eslint + prettier config, including vuex and router.
The error shows in the terminal of VSCode.
The steps I took was to change the helloworld stuff, renamed the default file to hud, and relevant details, It would then show the error, at the bottom of the file, as per the image kawazoe posted above.
@Tricky-Ricky I’m not too sure if I understand your last post correctly.
I did a fresh install without the linter, wrote the same code with no errors, and it displayed fine.
Tried again with the linter installed on a fresh install, same error…
Since this error is produced by the linter, it is not surprising that not installing it will not produce the error. This is irrelevant of the extensions or integration features your IDE provides. If you do not configure eslint, WebStorm will not show an error either, because it uses eslint to show your those errors.
The error shows in the terminal of VSCode.
Did you try running npm run lint
in the terminal or did you try something else to get this error? Can you post the log either as text or as a screenshot?
To be clear, my issue has been fixed a few WebStorm versions ago. It was definitely a bug in how WebStorm used eslint to look for errors, and not in this plugin, or in eslint.
I have similar error tried running npm run lint
but issue still persists. Just like @kawazoe mentioned at the bottom of the script tag. And I am not using webstorm either. Help please. IDE is VSCode.
I also get this error with @rollup/plugin-eslint 8.0.1
Same error with VSCode and vue-cli, my solution here is to add
public/index.html # or path to your html file with this problem
in my .eslintignore
file.
(Well, I know it’s a bad practice because it stops eslint from doing any check to the html file, not just the one bothers here.)
FYI when using -c
option, the "vue/comment-directive": 0
needs to be in the override.
Same here.
Only solution for me was to disable the rulerules: { 'vue/comment-directive': 'off' }
its useful. thx
This is what I ended up doing
// .eslintrc.js module.exports = { // ... overrides: [ { files: ['*.html'], rules: { 'vue/comment-directive': 'off' } } ] };
То же самое.
Единственным решением для меня было отключить правило
rules: {
'vue/comment-directive': 'off'
}
@vanderb да. Тоже сделал то же самое. Но похоже на лачугу.
По крайней мере, сейчас вам следует использовать переопределение, специфичное для html-файлов, поскольку вам, вероятно, все еще нужно это правило в файлах vue:
{
// HACK: https://github.com/vuejs/eslint-plugin-vue/issues/1355
files: ['**/*.html'],
rules: { 'vue/comment-directive': 'off' },
},
Почему вы линтуете HTML с помощью ESLint? eslint-plugin-vue поддерживает линтинг .vue
, но не .html
.
Если вы действительно хотите линтовать HTML, вам нужно применить процессор к .html
.
https://eslint.org/docs/developer-guide/working-with-plugins#specifying -processor-in-config-files
Я на самом деле не запускал его и не подтверждал, но я думаю, что он будет работать, если вы установите его следующим образом.
"overrides": [
{
"files": ["*.html"],
"processor": "vue/.vue"
}
]
@ ota-meshi Я действительно не знаю, стоит ли мне использовать его для .html
или нет. К сожалению, у меня еще нет такого опыта.
Но я создал приложение из интерфейса командной строки и хотел бы, чтобы не было ошибок. Итак, не могли бы вы объяснить мне, как правильно настроить ESLint? Достаточно ли использовать переопределение из вашего ответа или мне нужно еще кое-что узнать?
@ ota-meshi Проблема, похоже, вызвана тем, что правило применяется к обычным файлам HTML. Если вы посмотрите на OP, вы увидите, что он упоминает файл public/index.html
как вызывающий проблему. В любом случае это правило имеет смысл только в контексте файла vue, поэтому его отключение для файлов html, для которых оно не должно было быть включено изначально, имеет смысл.
Я не говорю, что мы должны включать его для файлов HTML. Я говорю, что он включен для них из коробки и не должен.
Добавление переопределения, которое я упомянул как есть, устраняет проблему, сохраняя при этом правило включенным для файлов vue, в отличие от предложения @vanderb , которое полностью отключает его.
ESLint по умолчанию не линтует .html
. Почему вы линтуете .html
с помощью ESLint?
Если вам не нужно применять ESLint к .html
, я думаю, вам следует исключить .html
. Я думаю, вы, вероятно, нацеливаетесь на .html
где-то в настройках.
Я не понимаю по-английски, поэтому могу не понять, что вы говорите правильно.
Думаю, я знаю, что происходит.
@ 4erkashin Вы используете WebStorm?
Я заметил, что при создании нового проекта с npx @vue/cli create foobar
и последующем запуске npm run lint
все хорошо.
Если я открою файл public/index.html
в WebStorm, я получу ошибку ESLint в среде IDE. Я думаю, что это может быть WebStorm, пытающийся связать каждый файл, который вы открываете, даже если у вас не настроен явный синтаксический анализатор для них.
Я до сих пор не знаю, почему в этом случае срабатывает vue/comment-directive
поскольку он должен быть привязан к **/*.vue
.
@kawazoe да, я использую веб-шторм. Понятно, спасибо за пояснение)
Должен ли я закрыть вопрос? Похоже, что это связано только с реактивными мозгами.
Вероятно, это проблема JetBrains.
Мой обходной путь по-прежнему будет работать для вас, если вы захотите использовать его, пока мы ждем от них исправления.
Если вы сообщите об этом в их трекере, можете ли вы связать его здесь, чтобы я тоже мог следить за ним?
@ 4erkashin, это действительно похоже на проблему с WebStorm. Мы собираемся исправить это на нашей стороне, вы можете закрыть проблему.
Была ли эта страница полезной?
0 / 5 — 0 рейтинги