0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

`.editorconfig`でスクリプト最終行の改行を自動で追加する

Posted at

背景

PRレビューで最終行に改行がないことをコメントいただくことがありました。
毎回手動で気をつけたくはないので、自動で検知・修正する方法を調べて、設定手順を備忘録としてまとめました。

.editorconfigとは?

.editorconfig は、エディタ間でコードスタイルの設定を共有するためのファイルです。
プロジェクトのルートディレクトリに .editorconfig を置くことで、対応エディタ(VSCode, IntelliJ, etc.)がそのルールに従って自動整形してくれます。

最終行改行の自動追加

.editorconfig を使って、自動的に最終行に改行を挿入するように設定します。
insert_final_newline = trueを使うことで、変更保存時に、最終行のフォーマットを実行してくれます。

.editorconfig
[*]
insert_final_newline = true

参考:https://editorconfig.org/#supported-properties

動作の確認

実際に手を動かしながらやってみます。

次のソースを用いて動作を確認していきます。
最終行に改行がないものです。

function hello() {
  console.log("Hello World");
}

1. .editorconfig をプロジェクトのルートに追加

touch .editorconfig

.editorconfigに以下の内容を追記します

[*]
insert_final_newline = true

2. エディタの設定

VSCodeの場合は、拡張機能「EditorConfig for VS Code」をインストールし、settings.json"editor.formatOnSave": true を設定。

Ctrl+Sで保存すると、スクリプトの最終行に改行が自動で追加されるようになります。

javascript
function hello() {
  console.log("Hello World");
}
+ 改行
他にも便利な設定
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
end_of_line = lf

それぞれ次のような意味です。

  • root = true:このディレクトリがプロジェクトのルートであることを示す
  • charset = utf-8:文字エンコーディングをUTF-8に統一
  • indent_style = space:インデントにスペースを使用(tabの場合はtab)
  • indent_size = 2:インデント幅を2文字に設定
  • insert_final_newline = true:ファイル末尾に改行を自動挿入
  • trim_trailing_whitespace = true:行末の余分な空白を削除
  • end_of_line = lf:改行コードをLF(Unix形式)に統一

参考:https://editorconfig.org/#supported-properties

ESLintによる方法

JavaScript / TypeScript プロジェクトであれば、ESLintのeol-lastルールを利用する方法もあります。

eslint.config.js
export default [
  {
    rules: {
      "eol-last": ["error", "always"]
    }
  }
];

参考:https://eslint.org/docs/latest/rules/eol-last#rule-details

こちらも一緒に試してみます。

npm install --save-dev eslint

ログ出力の記述しかないスクリプトを準備します(最終行に改行なし)。

console.log("test");
package.json
package.json
{
  "name": "editor-settings-js-test",
  "version": "1.0.0",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "lint": "eslint .",
    "lint:fix": "eslint --fix ."
  },
  "author": "",
  "license": "ISC",
  "keywords": [],
  "description": "",
  "devDependencies": {
    "eslint": "^9.30.1"
  }
}

npm run lint:fixを実行すると、改行が追加されていることを確認できました。

js
console.log("test");
+ 改行

まとめ

.editorconfig を導入することで、特定のエディタに縛られず最終行の改行問題を自動で解決できるのは嬉しいです。
人間がチェックしなくてもいいようにフォーマットは導入しておきたいものです。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?