2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

TypeScriptでprettier付きNode.jsのプロジェクトを作る際の手順

2
Last updated at Posted at 2019-10-31
  • プログラミング言語 TypeScript
  • コードフォーマッタ prettier

がセットアップされたNode.jsプロジェクトを作る手順の健忘禄。

最近、Prettierの公式が、 pretty-quick を使うようになったので修正。

配布されているNode.jsのインストーラーやnvmなどでNode.jsはインストール済みの前提。あとgitignoreやソースフォルダも作成。


mkdir myproject
cd myproject
npm init
echo node_modules >> .gitignore
echo dist >> .gitignore
mkdir src

ここまででプロジェクト作成。

次にTypeScriptとPrettierと各種定義やコミット時に自動フォーマットするためのライブラリなどをインストール。

npm i --save-dev typescript @types/node

次にtsconfig.json を作成。

npx tsc --init

tsconfig.json にコードのフォルダの指定と、出力先フォルダを作成。compilerOptionsの項目にて、

    "outDir": "./dist",                        /* Redirect output structure to the directory. */

を元のコメントアウトしているものと置き換え。コンパイル元のコードの設定を末尾に設定。

  }
 }

  },
 "include": [
   "src/**/*"
 ]
}

次に。package.jsonに各種便利スクリプトを設定、mainとscriptの項目を書き換え。

  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },

  "main": "src/index.ts",
  "scripts": {
    "start": "node dist/index.js",
    "build": "node_modules/.bin/tsc"
  },

Prettier の設定は好みで。自分は文字列は常にシングルクオーテーションにしたいのでこの設定で。

echo "singleQuote: true" >> .prettierrc

あとはコードを作成。

echo "console.log('Hello TS');" > src/index.ts

実行してみる。

npm run build && npm start

実行してみて、

Hello TS

と表示と表示されれば完了。

git init
git add .
git commit -am "First Commit"

Git に足して、あとは prettier 関連のインストールをする。

npm install --save-dev prettier husky 
npx husky-init
npm install --save-dev pretty-quick
npx husky set .husky/pre-commit "npx pretty-quick --staged"

src/index.ts を編集して

git commit -am "Test prettier"

これで

sifue@DESKTOP-LKSCKRS:~/workspace/serval-bolt$ git commit -am "Test prettier"
🔍  Finding changed files since git revision 466d18d.
🎯  Found 2 changed files.
✅  Everything is awesome!

のように表示されればちゃんと動いている。これをプッシュしてフォーマットされれば完成。では楽しいTypeScriptライフを!

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?