LoginSignup
1
0

More than 3 years have passed since last update.

Visual Studio CodeでTypeScriptのHTML開発環境作り

Posted at

はじめに

Visual Studio CodeでTypeScriptのHTML開発がしたい。
目指すはWebStormの"Compile on Change"程度に自動的にコンパイルしてくれて、かつtsconfig.jsonの"outFile"のようにファイルを1つにまとめること。
まるでFlash開発のように。

tsconfig.jsonで"outFile"を使うとなると、module:"amd"となります。
しかし、module:"amd"だと、vscodeがうまくimportできませんでした。
importをvscode側と合わせるために、とりあえずmoduleは"es2015"
そして、ファイルを一つにまとめるのはwebpackに任せることにします。

環境

OS Windows 10

VS Code
機能拡張
Live Server
Debugger for Chrome

設定方法

VSCodeで新しいフォルダを開きます。
メニューのターミナル/新しいターミナルでpackage.jsonを作ります。

npm init

続いて各種インストール

npm i -D webpack webpack-cli typescript ts-loader source-map-support

package.jsonを以下を追加、編集

package.json

...
"scripts": {
    "build": "webpack",
    "watch": "webpack -w"
  },
...
}

tsconfig.jsonを追加。
(VScod1.51.0はエラーがあるというが気にしない。)

tsconfig.json
{
    "compilerOptions": {
      "sourceMap": true,
      "target": "es5",
      "module": "es2015"
    },
    "exclude": [
        "node_modules"
    ]
}

webpack.config.jsを追加

webpack.config.js
module.exports = {
    //mode: 'production',
    mode: 'development',
    entry: './src/Main.ts',
    output: {
        path: `${__dirname}/script`,
        filename: "ts.js"
      },
    module: {
      rules: [
        {
          test: /\.ts$/,
          use: 'ts-loader',
        },
      ],
    },
    resolve: {
      extensions: [
        '.ts', '.js',
      ],
    },
    devtool : "source-map",
    watch : true
  };

TypeScriptファイル、src/Main.tsを作る。
起動確認のためにconsole.log("TypeScript Start");と入力。

index.htmlを作り、JavaScriptの読み込みの追加。

<script src="script/ts.js"></script>

ターミナル以下を入力して、ts.jsを生成。

npm run build

メニューの「実行/デバック」を選択して「Chrome」を選択して、.vscode/launch.jsonができる。
lanch.jsonのurlのポートを5500にする。

launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch Chrome against localhost",
            "url": "http://localhost:5500",
            "webRoot": "${workspaceFolder}",
            "preLaunchTask": "StartServer",
            "postDebugTask": "StopServer"
        }
    ]
}

LiveServerのサーバー起動。
VScode上のindex.htmlから「Open Width Live Server」を選び
それか、右下のGo Liveをクリック。
(ここままだと、VSCode上のコンソールには表示がない。

そして、 ターミナル以下を入力して、ウォッチモードを起動。

npm run watch

再度、「実行/デバック」すると、コンソールに表示の確認。
うまく行ってれば、ザクザク開発できる。

課題

もうちょっとスマートに行かないものかしら。
あとStartup Taskのように、起動時に「npm run watch」を入力せずに開発したいなぁ。

参考

git
https://github.com/kawamurashin/vsc_ts_webpack_source-map_template

最新版TypeScript+webpack 5の環境構築まとめ
https://ics.media/entry/16329/

1
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
1
0