LoginSignup
2
2

More than 5 years have passed since last update.

TypeScript + SystemJS + lite-serverでさくっとHello, World!する

Last updated at Posted at 2016-08-16

Angular2のチュートリアルをやり、tscとSystemJSの組み合わせは、TypeScriptで実験的なコードを書くには良いと感じた。

なるだけ最小構成で動かすために試したらこうなったので、メモとして残しておきます。

環境構築

とりま npm init

mkdir ts-sample
cd ts-sample
npm init -y

実験なので、-yで色々スキップ。

gitで管理する際には、package.jsonのrepository周りの情報が埋まるので先に git init を走らせておくのがよさ気。

必要なパッケージを追加する

npm i lite-server typescript typings concurrently --save-dev
npm i systemjs --save

※執筆時点でのバージョンは以下

  "devDependencies": {
    "concurrently": "^2.2.0",
    "lite-server": "^2.2.2",
    "typescript": "^1.8.10"
  },
  "dependencies": {
    "systemjs": "^0.19.36"
  }

SystemJSの設定

systemjsの設定ファイルを追加

touch systemjs.config.js
systemjs.config.js
System.config({
    baseURL: '/',
    transpiler: false,
    map: {
        'app': 'src/app' // dist
    },
    packages: {
        'app': { main: 'index.js' , defaultExtension: 'js' }
    }
});

TSCの設定

$(npm bin)/tsc --init

ファイル追加

TypeScriptファイルを追加

せっかくモジュールローダーを使っているので、2ファイル作る

mkdir src
cd src
touch index.ts hello.ts
index.ts
import { Hello } from './hello';

const hello = new Hello();
document.body.innerHTML = hello.message();
hello.ts
export class Hello {
    public message() {
        return 'hello, world!!';
    }
}

index.htmlを追加

index.html
<!DOCTYPE html>
<html>
    <head>
        <title>sample!?</title>
    </head>
    <body>
        <script src="./node_modules/systemjs/dist/system.src.js"></script>
        <script src="./systemjs.config.js"></script>
        <script>
            System.import('app');
        </script>
    </body>
</html>

読み込むのがsystemjs関係のみというのがシンプルで良い感じ

動かす

package.jsonにscriptを書く

package.json
...
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "tsc && concurrently \"tsc -w\" \"lite-server\" "
  },
...

消耗するので、実験レベルだとタスクランナー使いたくない派

hello, world!

npm run start

をすると、ブラウザが立ち上がり hello, world!!が表示されるはずです。

この状態で、hello, world!!を弄ると、ブラウザに変更が反映されます。
ざっくり仕組みとしては、

  • lite-server が *.js ファイルの変更を監視
  • tsc が *.ts ファイルの監視

を行っており、tsファイルをいじるとそれぞれが連動してブラウザに変更が反映されます。イイネ!

まとめ

あんまりさくっとじゃなかった

(参考)ディレクトリ構成

├── index.html
├── node_modules
├── package.json
├── src
│   ├── hello.js
│   ├── hello.ts
│   ├── index.js
│   └── index.ts
├── systemjs.config.js
├── tsconfig.json
└── typings.json
2
2
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
2
2