Очевидно, что стоит расширение BEM Helper
И у расширения есть настройки https://marketplace.visualstudio.com/items?itemNam…
Для bemHelper.classNameCase выставить одно из возможных значений: any, kebab, snake, camel, pascal, shoutingSnake.
Ответ написан
24 июн. 2022
1
комментарий
Warnings with the inline php
tag still causes invalid parsing but it a little bit another problem then has been described in that issue.
Description
Terminal problems tab shows a lot of warnings because it triggers on php
inline tag in non-class attribute. The class
is written without error but this is a problem with php
inline tags in other attributes like href
, src
, alt
etc. which are getting parsed. But they should not.
Example of code
<a class="navbar-brand" href="<?php echo esc_url( home_url() ); ?>">
note: after removing <?php ... ?>
warning is gone
Warning sample
BEM - Class names must be in kebab case
Plugin settings
VS Code setting.json
file
"bemHelper.showDepthWarnings": true, "bemHelper.classNameCase": "kebab", "bemHelper.responsiveLinting": true,
При использовании в веб-разработке методологии БЭМ (расшифровывается как «Блок, Элемент, Модификатор», у меня был о ней отдельный пост) неплохо было бы иметь инструмент для проверки имен классов на соответствие правилам именования классов в этой методологии.
Так как я сейчас учусь пользоваться редактором кода «VS Code», то поискал подходящее расширение в магазине расширений этого редактора:
https://marketplace.visualstudio.com/vscode
И нашел расширение «BEM Helper» (идентификатор: «Box-Of-Hats.bemhelper»), которое, судя по его описанию, подходит под мои нужды:
https://marketplace.visualstudio.com/items?itemName=Box-Of-Hats.bemhelper
Я установил это расширение в свою копию редактора «VS Code» и начал экспериментировать с ним. Оказалось, что это расширение мне не походит.
Существование нескольких схем именования
Дело в том, что в методологии БЭМ изначально была определена (компанией «Яндекс», внутри которой родилась эта методология) так называемая «классическая схема именования» классов CSS:
https://ru.bem.info/methodology/naming-convention/
Классическая схема именования выглядит примерно так (упрощенно):
имя-блока имя-блока__имя-элемента имя-блока имя-блока_имя-булевого-модификатора имя-блока имя-блока_имя-модификатора_значение-модификатора имя-блока__имя-элемента имя-блока__имя-элемента_имя-булевого-модификатора имя-блока__имя-элемента имя-блока__имя-элемента_имя-модификатора_значение-модификатора
Имя блока, имя элемента, имя булевого модификатора, имя модификатора со значением, значение модификатора являются именами, в которых пробел заменяется символом дефиса -
(в Юникоде символ U+002D, хотя это на самом деле не совсем дефис, а «дефис-минус», но его всё равно часто называют «дефисом»).
Такую схему написания имен (не только в методологии БЭМ, а вообще в программировании) называют по-английски «kebab case» или просто «kebab». Одно из значений слова «kebab» в английском языке — «шашлык». Тут ассоциация с тем, как при приготовлении шашлыка на шампур нанизываются кусочки мяса. Кусочками мяса выступают отдельные слова в имени, а между ними выглядывает «шампур» — дефисы.
Кроме того, как видно из примеров выше, в классической схеме именования используется три разделителя:
1. Разделитель имени блока и имени элемента: __
(два символа подчеркивания);
2. Разделитель, который отделяет имя блока или имя элемента от имени модификатора (хоть булевого, хоть модификатора со значением): _
(один символ подчеркивания);
3. Разделитель, который отделяет имя модификатора со значением от имени значения: _
(тоже один символ подчеркивания).
Однако, методология БЭМ позволяет придумывать и использовать альтернативные схемы именования классов CSS.
Схема именования классов CSS в «BEM Helper» по умолчанию
Расширение «BEM Helper» по умолчанию настроено на другую схему именования классов CSS. Эта схема описана тут:
http://getbem.com/naming/
Выглядит она примерно так:
имя-блока имя-блока__имя-элемента имя-блока имя-блока--имя-булевого-модификатора имя-блока имя-блока--имя-модификатора-значение-модификатора имя-блока__имя-элемента имя-блока__имя-элемента--имя-булевого-модификатора имя-блока__имя-элемента имя-блока__имя-элемента--имя-модификатора-значение-модификатора
Тут используются следующие три разделителя (пояснения см. выше, при объяснении «классической схемы именования»):
1. __
(два символа подчеркивания);
2. --
(два дефиса);
3. -
(один дефис).
Разница с «классической схемой именования» — в последних двух разделителях.
Настройка (параметры) «BEM Helper»
Расширение «BEM Helper» имеет параметры для настройки способа написания имен и разделителей. Вот они:
– bemHelper.classNameCase
(по умолчанию: kebab
, но возможны другие значения, а также можно выбрать сразу несколько и перечислить через запятую, возможные значения: «any», «kebab», «snake», «camel», «pascal», «shoutingSnake»);
– bemHelper.elementSeparator
(по умолчанию: __
(два символа подчеркивания));
– bemHelper.modifierSeparator
(по умолчанию: --
(два дефиса)).
Проблема расширения «BEM Helper»
Как я понимаю, расширение «BEM Helper» написано по принципам, изложенным на следующем сайте, который уже упоминался выше:
http://getbem.com/naming/
По вышеуказанной ссылке «модификатор со значением» называют «complicated modifier» (по-русски «сложный модификатор»), там в имя модификатора включается его значение. То есть, если смотреть с такой точки зрения, разделитель для модификатора со значением между именем модификатора и его значением не требуется, потому что они сливаются в единое целое.
Да, такая альтернативная схема именования классов CSS имеет право на существование, с ней можно работать. Однако, принципы этой схемы именования не позволяют настроить расширение «BEM Helper» для работы с «классической схемой именования», потому что при попытке такой настройки возникает конфликт, что подтверждает и сам автор данного расширения:
https://github.com/Box-Of-Hats/Bem-VSCode-Extension/issues/47
https://github.com/Box-Of-Hats/Bem-VSCode-Extension/issues/40
Цитата:
Hi, there is a restriction that you won’t be able to use the single — or _ characters as separators as they are used for kebab-case and snake_case classnames. If you instead use a double __ or — then the extension will work as expected
Мой перевод на русский:
Привет, существует ограничение: вы не сможете использовать одиночный — (дефис) или _ (символ подчеркивания) в качестве разделителей, так как они используются для имен классов CSS в стиле «kebab» и «snake». Если вы вместо них используете двойной __ (символ подчеркивания) или — (два дефиса), то расширение будет работать так, как ожидалось
Поэтому я пока что не стал работать с этим расширением и удалил его.
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
A VSCode extension to help when using the BEM (Block-Element-Modifier) class naming convention in HTML.
Get it on the VSCode Marketplace.
Got any feedback, issues or feature requests? Send them my way via GitHub Issues.
- BEM Helper
- Language Support
- Commands
- Settings
- Generating LESS / SCSS / CSS
- Inserting Elements
- Diagnostic Help
- Classes not following BEM standards
- Classes not following the specified case
Language Support
Currently, the languages that are officially supported are:
- HTML
- React (Jsx)
- React (Tsx)
- Razor (.net core / framework)
- Vue
- PHP
If there are any languages that you want support added for then please open a github issue
Commands
Command name | Description | Shortcut |
---|---|---|
bemHelper.insertBemElement | Insert a new BEM element under the current block | alt + b e |
bemHelper.insertBemModifier | Insert a new BEM modified element, copying the classname prefix of the previous element | alt + b m |
bemHelper.generateStyleSheet | Generate a new file containing CSS/LESS/SCSS for the current HTML file | alt + b s |
bemHelper.generateStyleSheetFromSelection | Generate a new file containing CSS/LESS/SCSS for the current selected elements | |
bemHelper.convertSelectionToCase | Convert the current text selection to a given case |
Settings
Setting | Description | Allowed Values |
---|---|---|
bemHelper.classNameCase | The allowed case styling of class names. Can be a single value or a list of values, separated by commas (e.g "kebab,snake" ) |
any, kebab, snake, camel, pascal, shoutingSnake |
bemHelper.responsiveLinting | Enable/disable linting checks whenever a file contents changes. Disable for increased performace. Reload window to take effect | true, false |
bemHelper.showDepthWarnings | Enable/disable depth warnings. e.g block__block2__element | true, false |
bemHelper.elementSeparator | The string to use as a separator for elements. By default is set to __ . Reload window to take effect |
any string |
bemHelper.modifierSeparator | The string to use as a separator for modifiers. By default is set to -- . Reload window to take effect |
any string |
bemHelper.sortGeneratedStylesheets | Controls whether generated stylesheets should be sorted alphabetically | true, false |
bemHelper.maxWarningsCount | The maximum number of diagnostic warnings to show. Defaults to 100. | number |
bemHelper.ignoreClassNames | A list of class names that should be ignored as parents (blocks) when inserting new elements or when generating a stylesheet. | A list of strings |
bemHelper.blockSelectionMode | The method to use for selecting a parent block when inserting elements | prefer-explicit, first-parent, explicit-only |
bemHelper.newLineAfterInsert | Should a newline be inserted after inserting an element? | true, false |
Generating LESS / SCSS / CSS
Generate stylesheets from your BEM markup using the generateStylesheet
command. When using LESS or SCSS, the classnames will be appropriately nested and ready for you to start styling.
If you don’t like fancy pre-processors, you can also generate plain CSS.
Inserting Elements
Both regular and modified element snippets can be inserted which already contain the parent class prefix. By default, these commands are bound to alt + b e
(insertBemElement
) and alt + b m
(insertBemModifier
), but they can be modified inside of the VSCode keyboard shortcuts menu.
Diagnostic Help
BEM helper provides warnings when class names are in violation of BEM naming standards.
Classes not following BEM standards
Classes not following the specified case
A quick fix is included to make fixing case name issues quicker.
You can specify your preferred casing in the extension settings using bemHelper.classNameCase
.