LoginSignup
17
18

More than 5 years have passed since last update.

Visual Studio Codeでnpmを使う

Last updated at Posted at 2016-03-31

この記事はVisual Studioを起動せず、CordovaでWindowsストアアプリを作るの続きです。ここに書かれていてよくわからないものについては、先の記事を確認してください。

さて、Visual Studio Codeでnpmを使います。npmを使うことで、プロジェクト内のライブラリバージョン管理を行うことができます。
このnpmを使ってライブラリのインストールを行っておくと、ライブラリの依存関係を解決してくれるほか、Gitのリポジトリにいちいちライブラリを追加しなくても、クローン先に簡単にライブラリをダウンロードすることができるので、リポジトリで管理するファイルが減らせます。

初期化処理

まず、プロジェクトの初期化処理を行います。npm initというコマンドを利用します。

> npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
・・・いろいろ質問・・・

質問のところで、いったんプロンプトが止まります。アプリ名やバージョン、概要、作者名などを聞かれますが、パッケージをアップロードするとかでもない限り、そんなに重要な情報ではないです。

すると、以下のようなファイルが出力されます。

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

なんか真ん中にErrorという文字列があるので一瞬不安になりますが、テスト用のコードなので問題ないです。

これで、モジュールインストールの準備が整いました。ここでは、Windowsストアアプリ向けのUIライブラリ、WinJSをインストールしてみます。

> npm install winjs --save
testapp@1.0.0 C:\temp\testapp
`-- winjs@4.4.0  extraneous

npm WARN testapp@1.0.0 No repository field.
  • 第一引数(winjs):インストールしたいパッケージ名
  • 第二引数(--save):依存ライブラリとして、package.jsonに保存する場合--saveをつける

インストールが終わりました。すると、カレントフォルダに、node_modulesというフォルダができると思います。これがモジュールがインストールされた場所です。

image

ためしに、このフォルダを削除して、もう一度npmからダウンロードしてみます。

> rm -rf node_modules
> npm install
testapp@1.0.0 C:\temp\testapp
`-- winjs@4.4.0

npm WARN testapp@1.0.0 No repository field.

packages.jsonに保存した依存ライブラリを全部ダウンロードしたいときには、引数無しで`npm install'コマンドを実行します。すると、ライブラリが全部インストールされます。

Visual Studio Codeから使う

Visual Studio Codeにも、npmの拡張があります。これを使うとnpmのコマンドをプロンプトを出さずに使えます。

まず、拡張機能をインストールします。拡張はそのままnpmです。
image

再起動すると、Command Paletteからnpmコマンドが一部使えるようになります。以下重要なコマンド

  • >npm: Initialize npm package: npm initです。最初に必ず必要。
  • >npm install and save dependency: npm install 〇〇 --save。パッケージ名はコマンド選択後に入力を促されます。
  • >npm: install saved packages:引数無しのnpm installです。復元時はこれを使いましょう。

Gitコミット時

ここまで書いておいてあえていうこともないですが、.gitignoreにはnode_modules/フォルダを指定しておきましょう。他はコミットして問題なしです。

17
18
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
17
18