ejsファイルPrettierフォーマット実行する覚書

2 min read
Prettierejs
hiroweb developer

前提

ejs は、HTML と<% %>を混在させて使用する。だが、Prettier は ejs のフォーマットに対応していないため、htmlフォーマットをかける必要がある。

prettier --parser html --write src/**/*.ejs

ejs を html フォーマットする問題

HTML のみの記述であれば全く問題ない。ただ、<% %>記法が混在する時に問題が起きるケースがある。

下記のような 1 行の記述であれば問題ないのだが、

<%- include('components/_page-title); %>

下記のような複数行に渡る記述の場合に問題が起こる。

<%-
  include('components/_page-title', {
    title: 'Multi-size item to choose by height and weight',
    description: 'Popular brand items at your ideal size',
    link: {
      url: 'https://example.com/',
      title: 'View all',
    },
  });
%>

上記を--parse htmlでフォーマットすると下記のようになってしまう。

<%- include('components/_page-title', { title: 'Multi-size item to choose by height and weight', description: 'Popular
brand items at your ideal size', link: { url: 'https://example.com/', title: 'View all', }, }); %>

記述を分断されて改行などが入ってしまうため、ejs としてビルドができなくなってしまう。

回避策

<!-- prettier-ignore -->を利用する。

ignore コメントを ejs 記法の前に記述しても意味をなさない。そのため、下記のように HTML 要素をラップして記述する必要がある。

<!-- prettier-ignore -->
<div>
<%-
  include('components/_page-title', {
    title: 'Multi-size item to choose by height and weight',
    description: 'Popular brand items at your ideal size',
    link: {
      url: 'https://example.com/',
      title: 'View all',
    },
  });
%>
</div>

こうすることで ejs の記述をフォーマットさせることなく、--parse htmlを実行することができる。

課題

<%
const foo = 1;
let bar = foo;

bar = 9;
%>

こういった HTML をラップする必要が皆無の場合、HTML を記述する箇所がほぼ皆無だったため、.prettierignoreに記述して回避した。