Mokelab Blog

Web アプリプロジェクトを作る

今回は npm などを利用して Web アプリプロジェクトを作ってみます。前提として、Node.jsがインストールされており、npm コマンドが使用可能とします。

プロジェクトの作成

まず、アプリプロジェクト用のフォルダを作りましょう。

$ mkdir demoapp
$ cd demoapp

そして、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>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (demoapp)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author: mokelab
license: (ISC) MIT
About to write to /(中略)/demoapp/package.json:

{
  "name": "demoapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "mokelab",
  "license": "MIT"
}


Is this OK? (yes) yes

最後にyesと入力すると、package.json が生成されます。これでプロジェクトができました。

$ ls
package.json

ついでに git リポジトリも作成し、いれておきましょう。

$ git init
Initialized empty Git repository in /(中略)/demoapp/.git/
$ git add package.json
$ git commit -m "Initial commit"
[master (root-commit) 01733ca] Initial commit
  1 file changed, 11 insertions(+)
  create mode 100644 package.json

Webpack の追加

Webpackとは js ファイルや css ファイルなどをいい感じにまとめてくれるツールです。ES6 module もいい感じにまとめてくれるので、プロジェクトに追加しましょう。開発時に使うものなので、--save-devをつけておきます。

$ npm install --save-dev webpack
(中略)
+ webpack@4.41.0
added 390 packages from 217 contributors and audited 4225 packages in 13.947s
found 0 vulnerabilities

package.json にスクリプトを追加

この時点で、package.jsonを見てみましょう。次のような形になっています。

{
  "name": "demoapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "mokelab",
  "license": "MIT",
  "devDependencies": {
    "webpack": "^4.41.0"
  }
}

scroptsのところでは、npm run で実行できるコマンドを記述します。testが用意されているので、試しに実行してみましょう。

$ npm run test

> demoapp@1.0.0 test /(中略)/demoapp
> echo "Error: no test specified" && exit 1

Error: no test specified
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! demoapp@1.0.0 test: `echo "Error: no test specified" && exit 1`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the demoapp@1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/fkm/.npm/_logs/2019-09-30T01_28_07_943Z-debug.log

test のところに記述されていた echo \"Error: no test specified\" && exit 1 が実行されました。exit 1 が付いているので、エラーとして報告もされています。

ここに、先ほど追加したwebpack によるビルドスクリプトを追加しましょう。といっても実行するのはwebpack コマンドだけです。package.jsonscripts の部分を次のように編集します。

"scripts": {
  "build": "webpack",
  "test": "echo \"Error: no test specified\" && exit 1"
},

追加したら、早速実行してみましょう。

$ npm run build

> demoapp@1.0.0 build /(中略)/demoapp
> webpack

One CLI for webpack must be installed. These are recommended choices, delivered as separate packages:
  - webpack-cli (https://github.com/webpack/webpack-cli)
    The original webpack full-featured CLI.
We will use "npm" to install the CLI via "npm install -D".
Do you want to install 'webpack-cli' (yes/no):

webpack-cli が必要そうなので、yesを入力してインストールしてしまいましょう。インストールが終わると続けてwebpack コマンドが実行されます。

ERROR in Entry module not found: Error: Can't resolve './src' in '/(中略)/demoapp'

srcフォルダがないよというエラーが出ました。webpackの実行自体はできているようです。

webpack.config.js を用意する

webpackwebpack.config.jsという設定ファイルを読み込んでファイルをまとめてくれます。 package.jsonがあるフォルダに作成しましょう。

module.exports = {
    mode: "development",

    entry: "./src/main.js",

    module: {
        rules: []
    },

    resolve: {
        extensions: [".js"]
    }
};

後の記事で項目は増やしていきます。

次に、srcフォルダを作り、main.jsファイルを(とりあえず)用意しましょう。

$ mkdir src
$ cd src
$ echo "console.log('Hello web app');" > main.js
$ cd ..

ファイルの用意ができたら、npm run buildwebpackを実行してみましょう。

$ npm run build

> demoapp@1.0.0 build /(中略)/demoapp
> webpack

Hash: 76373c8fed5385fbbac6
Version: webpack 4.41.0
Time: 64ms
Built at: 2019/09/30 11:52:53
  Asset      Size  Chunks             Chunk Names
main.js  3.79 KiB    main  [emitted]  main
Entrypoint main = main.js
[./src/main.js] 30 bytes {main} [built]

ビルドが成功すると、distフォルダに成果物となるmain.jsファイルができました。

$ ls dist/
main.js

最後に、必要なファイルを git にいれておきましょう。node_modulesと成果物は除外しておきましょう。

$ echo 'node_modules/' > .gitignore
$ echo 'dist/main.js' >> .gitignore
$ git add .
$ git commit -m "Initial commit"
[master 7d7bd53] Initial commit
  5 files changed, 4054 insertions(+), 1 deletion(-)
  create mode 100644 .gitignore
  create mode 100644 package-lock.json
  create mode 100644 src/main.js
  create mode 100644 webpack.config.js

まとめ

npm init からwebpackによるビルドまでを行うプロジェクト作成を説明しました。ここまでの作業内容をテンプレートとして用意しておくと便利かもしれません。

本サイトではサービス向上のため、Google Analyticsを導入しています。分析にはCookieを利用しています。