LoginSignup
15

More than 5 years have passed since last update.

コードからtextlintを実行する

Last updated at Posted at 2017-04-12

概要

textlintはテキスト向けのLintツールで、予め定義したルールに沿って文章校正を行ってくれます。textlintの利用方法としてCLIから利用することが多いと思いますが、コードからtextlintを実行する必要があったので調査しました。この投稿はそのメモです。

環境構築

Node.jsのインストール

Node.jsのバージョンはv6.9.1を使用しています。nvmnodebrewなどを使ってインストールします。

textlintのインストール

textlint本体をインストールします。

npm install textlint

ルールのインストール

textlintを実行する際に使用するルールをインストールします。今回はtextlint-ja/textlint-rule-preset-ja-technical-writingを使用します。

npm install textlint-rule-preset-ja-technical-writing

.textlintrcの設定

.textlintrcを作成し"preset-ja-technical-writing"をtrueにしておきます。

{
  "rules": {
    "preset-ja-technical-writing": true
  }
}

textlintの実行

コードから実行する場合以下のようになります。TextLintEngineCore#executeOnTextを使用すると引数に取ったテキストに対してtextlintを実行することができます。引数にファイルを指定したい場合TextLintEngineCore#executeOnFilesを使用します。

const TextLintEngine = require("textlint").TextLintEngine;

const engine = new TextLintEngine({
    rulePaths: [
      "node_modules/textlint-rule-preset-ja-technical-writing"
    ]
});

engine.executeOnText("# test!!").then(results => {
  console.log(results[0].messages);

  if (engine.isErrorResults(results)) {
    const output = engine.formatResults(results);
    console.log(output);
  }
});

実行結果は以下のように出力されます。

node index.js

[ { type: 'lint',
    ruleId: 'preset-ja-technical-writing/no-exclamation-question-mark',
    message: 'Disallow to use "!".',
    index: 6,
    line: 1,
    column: 7,
    severity: 2 },
  { type: 'lint',
    ruleId: 'preset-ja-technical-writing/no-exclamation-question-mark',
    message: 'Disallow to use "!".',
    index: 7,
    line: 1,
    column: 8,
    severity: 2 } ]

<text>
  1:7  error  Disallow to use "!"  preset-ja-technical-writing/no-exclamation-question-mark
  1:8  error  Disallow to use "!"  preset-ja-technical-writing/no-exclamation-question-mark

✖ 2 problems (2 errors, 0 warnings)

サンプルコード

サンプルコードはこちらです。

参考

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
15