旧プログラマーによる日曜プログラミング日記

趣味は作曲、自分で一から作りたがりのユーザIT子会社の旧プログラマーによるリハビリのための日曜プログラミング日記です。

Phaser3+typescriptでSRPGを開発してみる #002 環境設定

ということで、まずは環境設定からスタートしてみようかなと思います。

但し、まだ納得いく環境設定ができておらず、随時更新を入れようかと思います。

環境設定

今回、私はVisual Studio Code(VSCode)で環境設定してみました。

1. 前提条件

(1) MacOSX 10.14を使用

(2) Node.jsのインストール

Node.jsについては今回は詳しく説明しませんが、まずはインストールしてください。

nodejs.org

(3) VSCodeのインストール

Visual Studio Codeについてもインストール方法は他のブログ等見れば載っていますので、そちらを見ていただいた方が早いかもです。

azure.microsoft.com

(4) VSCodeの設定

そしてそのVSCodeの設定が必要です。

Node.js Modules Intellisenseのインストール

左バーの上から5番目の「拡張機能」を選択して、上部に出てきたテキストボックスにNode.jsと入れます。f:id:mtmusic34:20210612112742p:plain そして、クリックして右側に情報が出てきたらインストール(写真では既にインストール済なので「アンインストール」と出てきてますが)が可能です。

ESLintのインストール

同じく、左バーの上から5番目の「拡張機能」を選択して、上部に出てきたテキストボックスにESLintと入れます。

f:id:mtmusic34:20210612112441p:plain
ESLintインストール

2. 手順

1. プロジェクトを作る

f:id:mtmusic34:20210612113136p:plain
プロジェクト作成
こちらで「開く」を選択し、このプロジェクトを作りたいフォルダを選び、右下の「開く」ボタンを押します。
f:id:mtmusic34:20210612113230p:plain
プロジェクトを開く(新規だけど)
f:id:mtmusic34:20210612113402p:plain
VSCode メイン画面

2. ターミナルで関連するライブラリを取得する

ここで、ターミナルを起動します。

f:id:mtmusic34:20210612113658p:plain
Terminalの起動

(1) npm初期化(package.jsonの作成)

$ npm init -y

(2) typescriptのインストール

typescriptのモジュールをインストールします。このタイミングでpackage-lock.jsonとnode_modulesフォルダが作成され、node.jsのライブラリは、node_modulesフォルダの中に格納されます。

$ npm install typescript --save
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN hatena@1.0.0 No description
npm WARN hatena@1.0.0 No repository field.

+ typescript@4.3.2
added 1 package from 1 contributor and audited 1 package in 3.152s
found 0 vulnerabilities
$

また、package.jsonも「--save」オプションにより書き換わり、dependenciesタグに、下記のように記載されます。

  "dependencies": {
    "typescript": "^4.3.2",
  }

(3) webpack関連のインストール

typescriptからjavascriptへのトランスパイル(コンパイルのようなもので、別の言語への自動書き換えのこと)や、 開発サーバの準備、トランスパイル対象の読み込み等を実施してくれるビルド関連のソフトウェアもインストールします。

実はPhaser3はWeb Serverが無いと動きません。

単体テスト環境としてはいったん、Webpackのサーバを使おうかと思います。 VSCodeだとLive Serverも利用可能です。

本番アップロードするときには、、また考えます。

$ npm install webpack webpack-cli webpack-dev-server ts-loader expose-loader  --save
npm WARN deprecated chokidar@2.1.8: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.
npm WARN deprecated fsevents@1.2.13: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.
npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated

> fsevents@1.2.13 install /Users/mt/Programs/nodejs_vscode/hatena/node_modules/fsevents
> node install.js

  SOLINK_MODULE(target) Release/.node
  CXX(target) Release/obj.target/fse/fsevents.o
  SOLINK_MODULE(target) Release/fse.node
npm WARN hatena@1.0.0 No description
npm WARN hatena@1.0.0 No repository field.

+ webpack-dev-server@3.11.2
+ ts-loader@9.2.3
+ webpack-cli@4.7.2
+ webpack@5.38.1
+ expose-loader@3.0.0
added 534 packages from 328 contributors and audited 535 packages in 25.981s

32 packages are looking for funding
  run `npm fund` for details

found 1 moderate severity vulnerability
  run `npm audit fix` to fix them, or `npm audit` for details
$

(4) Phaser3をインストールする

同じくPhaser3のインストールです。

$ npm install phaser --save
npm WARN hatena@1.0.0 No description
npm WARN hatena@1.0.0 No repository field.

+ phaser@3.55.2
added 5 packages from 3 contributors and audited 540 packages in 6.919s

32 packages are looking for funding
  run `npm fund` for details

found 1 moderate severity vulnerability
  run `npm audit fix` to fix them, or `npm audit` for details
$

ちなみに--saveオプションを忘れたら、package.jsonを直接直してもいいですし、もう一度--saveオプション付けて実行しても、大して問題ではありません。

3. 環境設定ファイルを作成・修正する

(1) webpack.config.js ファイルを作成

コンパイルを正常に動かすために、webpack.config.jsファイルを新規で作成します。

webpack.config.js

const path = require("path");
const phaserModulePath = path.join(__dirname, "/node_modules/phaser/");
const phaser = path.join(phaserModulePath, "dist/phaser.js");

module.exports = {

    mode: 'development', // "production" | "development" | "none"

    // メインとなるJavaScriptファイル(エントリーポイント)
    entry: './src/index.ts',

    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "index.js"
    },
    target: 'node',

    module: {
        rules: [
            //.tsがつくファイルを探索し、Typescriptとして読み込む(ts-loader)
            { test: /\.ts$/, loader: "ts-loader", exclude: "/node_modules/" },
        ]
    },
      //開発用サーバを立てるときの設定
    devServer: {
        contentBase: path.resolve(__dirname, "./"),
        publicPath: "/dist/",
        host: "127.0.0.1",
        port: 5500,
        open: true
    },
    // パス解決のための設定で、import 文で ライブラリ読み込みに必要
    resolve: {
        modules: [
        "node_modules", // node_modules 内も対象とする
        ],
        extensions: [ // 拡張子
        '.ts',
        '.js'
        ],
        alias: {
            phaser: phaser // プラスPhaserのモジュールもパス解決
        }
    }
};

(2) package.jsonを修正する

script属性を更新し、npmコマンド実行時のロジックを定義します。

package.json

  "scripts": {
    "tsc": "tsc",
    "build": "webpack --mode production",
    "debug": "node",
    "dev": "webpack --mode development && webpack serve --open 'Google Chrome' --config ./webpack.config.js"
  },

これで、 npm run buildとやるとビルドを実行でき、npm run devとやると開発用javascriptでトランスパイルした後に、Google Chromeが立ち上がり、実際に動き始めるはずです。

この辺りはまた研究次第、ナレッジを追記いたします。

(3) tsconfig.jsonを作成する

typescriptのコンパイルオプション用のファイルであるtsconfig.jsonを作成します。 tscコマンドが打てなかったので、node_modulesの下に展開されたbinを使いました。

$  node_modules/typescript/bin/tsc --init
message TS6071: Successfully created a tsconfig.json file.
$

その上でいくつか直しています。

tsconfig.json

     :
    "outDir": "dist/",                              /* Redirect output structure to the directory. */
     :
    "strict": false,                                 /* Enable all strict type-checking options. */
     :
    "moduleResolution": "node",                     /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    "baseUrl": "./",                                /* Base directory to resolve non-absolute module names. */
    "paths": { "@src/*" : ["src/*"] },              /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
     :
    "skipLibCheck": true,                           /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true        /* Disallow inconsistently-cased references to the same file. */

この辺りです。

outDir

出力先フォルダを明示的に指定しました。//コメントアウトを消して、値として"dist/"を設定しています。

strict

これもまだtypescript初心者だったので、falseにしておきました。この辺りは好みですかね。

paths

ここも研究中ですが、tsファイルのモジュール読み込みに相対パスでなくて絶対パスが使いたくて、@srcエイリアスとして使えるように設定しています。

が、まだここの効果は見れてないです(今後検証して、結果をお伝えできればと)。今は相対パスで書いています。

jestで実行するときに、パスが変わったりして見えなくなっていて・・・何か設定がおかしそうです。。

(4) launch.jsonに手を入れる

あと、VSCodeデバッグするために、launch.jsonに起動設定を書き込みます。

まずは、下記に従って、適当な構成(node.jsとかで良いかな)を選んで、ファイルを作成します。

f:id:mtmusic34:20210612121113p:plain
launch.jsonの初回作成

すると、JSONが開くので、下記設定を加えます。

launch.json

{
    // IntelliSense を使用して利用可能な属性を学べます。
    // 既存の属性の説明をホバーして表示します。
    // 詳細情報は次を確認してください: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [    
    {
        "type": "chrome",
        "request": "launch",
        "name": "Launch Chrome against localhost",
        "url": "http://localhost:5500",
        "webRoot": "${workspaceFolder}"
    },
    {
        "type": "node",
        "request": "launch",
        "name": "Launch from npm script",
        "runtimeExecutable": "/usr/local/bin/npm",
        "runtimeArgs": [
          "run", "test", "--silent=false", "--verbose" , "false"
        ],
        "protocol": "inspector",
        "port": 9229
    }
    ]
}

ゆくゆくはJestの設定も加えようと思いますが、まだ本格的にJestソースコードを作成できていないので、 一旦ここまでにしましょうか。

これで、VSCodeデバッグと、npmコマンドによるビルド、ビルド後にWebServer立ち上げて実行などができるようになりました。

いくつか、ファイルパス等も入っていますが、ファイルの作成などは#003にてお伝えしようかと思います。

それでは!

mtmusic34.hatenablog.com

過去の日記

タイトル 記載内容
#001 プロローグ Phaser3とは