HTMLHintはURLを直接指定してチェックをすることもできる

HTMLHintとは

HTMLの構文チェックができるもの。

例えば以下のHTMLには問題があるのだが、何が問題かわかるだろうか。

https://iwb.jp/s/htmlhint-can-check-url-code-directly/

<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="robots" content="none">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hello world!</title>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>

答えはDoctypeが最初に記述されていない。

HTMLHintを使用するとDoctypeの記載漏れなどを検出できる。

$ htmlhint *.html
 /Users/i/sample/index.html
       L1 |
           ^ Doctype must be declared first. (doctype-first)
 Scanned 1 files, found 1 errors in 1 files (15 ms)

HTMLHintは以下のコマンドでインストールできる。

npm install htmlhint -g

URLを直接指定してチェックも可能

HTMLHintはURLを直接指定してチェックすることも可能になっている。

例えばhtmlhintのあとに先程のURLを入れて実行すれば同様にHTMLHintで検出することができる。

$ htmlhint https://iwb.jp/s/htmlhint-can-check-url-code-directly/
       L1 |
           ^ Doctype must be declared first. (doctype-first)
 Scanned 1 files, found 1 errors in 1 files (15 ms)

ルールの設定方法

htmlhintはそのまま使用すると検出したくないものと引っかかるので.htmlhintrcファイルを作成して以下のようにルールを設定したものを読み込まないと使い勝手が悪い。

各ルールの詳細に関しては公式ドキュメントを参照。

https://htmlhint.com/docs/user-guide/list-rules

設定例

{
   "doctype-first": true,
   "doctype-html5": true,
   "head-script-disabled": false,
   "style-disabled": false,
   "title-require": true,
   "attr-lowercase": ["viewBox"],
   "attr-no-duplication": true,
   "attr-no-unnecessary-whitespace": true,
   "attr-unsafe-chars": true,
   "attr-value-double-quotes": true,
   "attr-value-not-empty": false,
   "alt-require": true,
   "input-requires-label": true,
   "tags-check": false,
   "tag-pair": true,
   "tag-self-close": false,
   "tagname-lowercase": true,
   "empty-tag-not-self-closed": true,
   "src-not-empty": true,
   "href-abs-or-rel": false,
   "id-class-ad-disabled": false,
   "id-class-value": true,
   "id-unique": true,
   "inline-script-disabled": false,
   "inline-style-disabled": false,
   "space-tab-mixed-disabled": true,
   "spec-char-escape": true
 }

設定したファイルはこのように読み込んで実行する。

htmlhint --config .htmlhintrc https://iwb.jp/s/htmlhint-can-check-url-code-directly/