はじめに
なおvagrant上のarchでの開発を前提としている
最終的な流れ
1. サーバー起動
$ npm run start
2. 自動ビルドを起動
$ npm run build
3. 後はソース書くだけ
設定
1. Vagrant内とのネットワークを作る
Vagrantfile
で以下をアンコメント
config.vm.network "private_network", ip: "192.168.33.10"
2. expressを入れる
vagrant内のファイルには直接アクセスできないので必然的に必要となる
$ npm i -D express
// app.js var express = require('express') var app = express() app.use(express.static('dist')); app.get('/', (req, res) => { res.sendFile('dist/index.html', { root: __direname }) }) app.listen(3000)
これで$ node app.js
した状態で192.168.33.10:3000
にアクセスするとdist/index.html
が見れる
3. nodemonを入れる
$ node app.js
コマンドでは、index.html
を変更してブラウザを更新しても反映されないが(毎回$ node app.js
で再起動が必要)nodemonなら自動で反映させてくれる
$ npm i -D nodemon
これで$ npx nodemon app.js
とすればよい
せっかくなのでpackage.json
に設定を書いてnpm run start
で起動するようにする
// package.json { ... "main": "app.js", "scripts": { "start": "nodemon" } }
4. webpackの設定をする
// webpack.config.js const path = require('path'); module.exports = { mode: 'development', devtool: 'inline-source-map', entry: './src/scripts.ts', output: { filename: 'bundle.js' path: path.resolve(__dirname, 'dist') }, module: { rules: [ { test: /\.ts$/, use: 'ts-loader' } ] } };
// package.json { ... "main": "app.js", "scripts": { "build": "webpack --watch", "start": "nodemon" } }
--watch
オプションをつけることで、.ts
ファイルを更新すると自動でコンパイルしてくれる
実行画面
これで最初のコマンドを、端末2つ使って実行するだけで開発できる
$ npm run start
$ npm run build