LoginSignup
1
0

More than 1 year has passed since last update.

【npm】Nodejsプロジェクトの準備

Last updated at Posted at 2022-08-10

想定する環境

  • OS: Windows10
  • コードエディターにVisual Studio Codeを使用している
  • Nodejs インストール済み

1. 作業用ディレクトリの作成

最初に、プロジェクトで使用するディレクトリを、任意の場所に作成します。

> cd /d D:\NpmProjects
> mkdir Sample
> cd Sample

2. プロジェクトの初期化

作成したディレクトリでnpm initコマンドを実行することで、package.jsonファイルを作成できます。また、--yesオプションを追加することで、REPLによる入力要求をスキップできます。

> npm init --yes

以下のように、package.jsonファイルが作成されていれば成功です。

package.json
{
  "name": "sample",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

3. 便利なツールのインストール

開発を効率よく進めるため、いくつかの便利なパッケージをインストールします。

rimraf

クロスプラットフォームな環境で UNIX コマンドのrm -rfと同等の機能を実現します。

> npm i -D rimraf

これを利用して、typescriptなどでビルドした結果を都度削除することで、再ビルドを容易にします。

package.json
{
  ...,
  "scripts": {
    "pre<scriptName>": "rimraf <出力先>",
    "<scriptName>": "<コマンド>"
  }
}

この例は、Pre & Post Scripts 機能を利用して、ビルド時に出力先が存在した場合、削除します。

npm-run-all

複数のNPMスクリプトを、並列または順番に実行するためのCLIツールです。

> npm i -D npm-run-all

標準のnpm runコマンドは、複数のスクリプトを実行する場合に記述が冗長になります。

npm-run-allを使用すると、globのようなパターンでコマンドを記述できるようになります。

  • run-s: 順番に実行
  • run-p: 並列に実行
package.json
{
  "scripts": {
    "build": "run-p build:*",
    "build:cjs": "<コマンド>",
    "build:esm": "<コマンド>"
  }
}
1
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
1
0