LoginSignup
0
0

More than 3 years have passed since last update.

Node.js新規アプリケーション作成時の初期設定手順

Last updated at Posted at 2020-07-30

前提条件
・node.jsがインストールされていること

手順

1: 任意の場所に、アプリケーションを格納するフォルダを作成する
・・・今回はデスクトップにnodeフォルダを作成
 

2: コマンドプロンプトにて下記コマンドを入力し、package.jsonを生成する

入力
> cd C:\Users\yamapi1012bs\Desktop\node
#              ↑ユーザー名

> npm init --yes
# package.jsonがフォルダに生成される
#以下のように出力されればOK
Wrote to C:\Users\yamapi1012bs\Desktop\node\package.json:

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

>

 
 
3: npmパッケージをインストールする

入力
> npm install express ejs nodemon
# 今回は、expressとejsとnodemonの3つのパッケージをインストール
# 以下のように出力されればOK

> node --harmony ./postinstall.js

Thank you for installing EJS: built with the Jake JavaScript build tool (https://jakejs.com/)

npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN node@1.0.0 No description
npm WARN node@1.0.0 No repository field.

+ express@4.17.1
+ ejs@3.1.3
added 65 packages from 44 contributors and audited 65 packages in 18.403s
found 0 vulnerabilities

>

 

nodeフォルダ内に

  • node_modules(フォルダ)
  • package.json
  • package-lock.json

が生成されていれば設定完了
 

実行してみる

1: nodeフォルダ内に以下を作成

  • index.js
  • views(フォルダ)
    • sample.ejs(viewsフォルダ内)
index.js
const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.render('sample.ejs');
});

app.listen(3000);
sample.ejs
<h1>Hello World</h1>

2: コマンドプロンプトにて下記コマンドを入力

入力
> node index.js

3: ブラウザを開いて「localhost:3000」にアクセス
sample.ejs(Hello World)が表示されればOK

ファイル更新時に自動でサーバーを再起動させる

※必須ではないですが、デバッグ時に役立ちます
 この設定をしておらず30分近くハマったことがあるのは内緒

前提条件
・nodemonパッケージがインストールされていること

1: package.jsonのscripts欄を下記の通り修正する

package.json
"scripts": {
    "start": ".\\node_modules\\.bin\\nodemon app.js"
  },

2:コマンドプロンプトにて下記コマンドを入力

入力
> npm run start

終わり。

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