11
2

More than 5 years have passed since last update.

Monaco Editorでprettierをフォーマッタとして登録する

Posted at

技書博では東京ラビットハウスというサークルでEffective React Hooksという本を出そうと執筆中のerukitiです。今回はその執筆過程ででてきたものを記事にしています。

Monaco Editor で CMD/CTRL + S をセーブっぽい挙動にする - Qiitaと関連する記事なのですが、タイトルの通りです。

Monaco Editorにフォーマッタを登録する

monaco.languages.registerDocumentFormattingEditProvider('javascript', {
  async provideDocumentFormattingEdits(model) {
    const prettier = await import('prettier/standalone')
    const babylon = await import('prettier/parser-babylon')
    const text = prettier.format(model.getValue(), {
      parser: 'babel',
      plugins: [babylon],
      singleQuote: true,
      tabWidth: 2
    })

    return [
      {
        range: model.getFullModelRange(),
        text
      }
    ]
  }
})

monaco.languages.registerDocumentFormattingEditProviderを呼び出して、フォーマットするコールバックを登録するだけです。

babylonは、Babelのパーサーの以前の名前です。そのため、{parser: 'babel'}を指定するのですが、プラグインの名前は未だにprettier/parser-babylonというのが解せないですが、そういうものです。たぶん。

ここで登録するプロバイダ関数は、編集履歴を配列に入れて返す物です。{range: model.getFullModelRange()}によってエディタのテキスト全体を、変換済みのtext でリプレースするというものです。

もちろん、rangeを別のものにすれば、特定の範囲を削除、置換したり、追記したりすることができますが、インクリメンタルパーサーの仕組みとかを使っていれば話は別かもしれませんが、FormattingEditProviderでそういうことをする機会はあまり無いでしょう。

11
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
2