Djangoroidの奮闘記

python,django,angularJS1~三十路過ぎたプログラマーの奮闘記

Angularのための、TypeScript入門 その5

参考サイト

https://www.codingforentrepreneurs.com/projects/getting-started-typescript/ https://www.codingforentrepreneurs.com/blog/typescript-setup-guide/

Package.json - npm init

  • package.jsonを作成する(djangoでいうところの、requirements.txtにあたるところ?)

  • $npm initをターミナルに打ち込む。あとは手順通りに項目を入力していくと、package.jsonが自動で作成される。

  • $npm testなど任意のコマンドを登録できる。以下のように登録すると、$npm run mainとターミナルにコマンドをうつと、webpack --watch --optimize-minimizeが実行される。

"scripts": {
  "main": "webpack --watch --optimize-minimize",
  "server": "http-server -c-1",
  "test": ""
},

jQuery, Typings, and npm

  • $ npm install typingsをinstallする。

  • ただこの時点では、package.jsonには、typingsのinstallが反映されていない。

  • $ typings install dt~jquery --global --saveを実行する。(globalだとうまくいかない場合は、localで処理する)

  • $ typings installを実行する。(うまくいかない場合は、localにtypingsをinstallするとかかな)

  • tsconfig.jsonにtypings以降のフォルダも参照にするように記載する。

{
  "compilerOptions": {
    "module": "commonjs",
    "outDir": "dist/",
    "noImplicitAny": true,
    "removeComments": true,
    "preserveConstEnums": true
  },
  "include": [
    "src/*",
    "typings/*"
  ],
  "exclude": [
      "node_modules",
      "**/*.spec.ts"
  ]
}
  • main.ts にimportして、jqueryのコードを書いてみる。
import * as $ from "jquery";
import { MustHaveCoffee } from './coffee/getcoffee';

class ReallyCoffee extends MustHaveCoffee {
  coffeeType = 'tenshi';
  constructor(){super()}  
    f(input: boolean){
      let a = 100
      if (input) {
        let b = a + 100012
        return b;
      }
      return a;
    }
    setCoffeeType(name:string){
      console.log("hello there " + "test " + this.coffeeType)
      $("body").css('background-color', 'red') // ここがjquery
      $("body").html("<h1>" + this.coffeeType + "</h1>")
    }
}

let newCoffee = new ReallyCoffee();
newCoffee.f(true);
newCoffee.setCoffeeType("bulletproof");

let odlCoffee = new MustHaveCoffee()
  • $npm run serverすると、以下のerrorが出てしまう。
ERROR in ./src/main.ts
Module not found: Error: Can't resolve 'jquery' in '/path/tsSetup/src'
 @ ./src/main.ts 13:8-25
  • $npm link jqueryで、localと、globalのjqueryをlinkさせる?とうまくいった!

  • $npm install jquery --save というように、saveをつけて実行するとpackageにinstallされる。