Angularのための、TypeScript入門 その5
参考サイト
https://www.codingforentrepreneurs.com/projects/getting-started-typescript/ https://www.codingforentrepreneurs.com/blog/typescript-setup-guide/
Package.json - npm init
$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される。