{%hackmd BJrTq20hE %} ###### tags: `TypeScript` # TypeScript 什麼是TypeScript,TS是用來解決JavaScript弱形別所產生的問題,那就是程式要執行之後才能知道哪邊的資料是因為型別不對而報錯,TS可以在程式執行前檢查可能出錯的地方。 ## 安裝TypeScript 1.先安裝node.js(建議可以使用nvm) 2.輸入node -v 可以查訊版本 ![](https://i.imgur.com/oxmyHSU.png) 3.打開命令題是字元 4.輸入以下安裝 ``` npm install -g ``` 5.輸入tsc -V 有出現版本就帶表裝好了 ![](https://i.imgur.com/8oINL7g.png) ## 創建一個簡單的TypeScript專案 1.建立一個資料夾 2.建立一個.ts的檔案 3.輸入TypeScript 程式碼 ``` let mystring : string = "Hello"; ``` 4.輸入tsc "檔案名稱".ts 進行編譯 ![](https://i.imgur.com/A5hysCD.png) 5.編譯完成 ![](https://i.imgur.com/aAEtjPR.png) ## TypeScript Config 一個方便把ts編譯為js的工具,一般來說專案都會有多個ts檔,一個一個進行編譯太不方便。 ### 1.開始使用TypeScript Config 輸入 ``` tsc --init ``` ![](https://i.imgur.com/K0eqx7V.png) 會出現下面的檔案 ![](https://i.imgur.com/ModfRQ0.png) ### 2.TypeScript Config 打開tsconfig.json #### rootDir 為輸入TS檔案的位置一般來說會如下設定 "rootDir": "./src", 代表在src內的.ts都編譯為js #### outDir 為編譯ts後要輸出為js的位置一般來說會如下設定 "outDir": "./dist", #### sourceMap 為編譯後可以透過開發者工具直接找到.ts檔,如果這一項沒有打開的話,在開發者工具看到的只會是編譯後的js檔。 再有打開sourceMap設定的情況下輸入tsc後會看到sorcemap如下圖 ![](https://i.imgur.com/ox542lZ.png) 此時可以看到透過sorcemap可以直接看到hell的來源是index.ts 如下圖 ![](https://i.imgur.com/TOLt2ju.png) 如果再沒有sourceMap的情況下只會看到編譯後的js檔 如下圖 ![](https://i.imgur.com/adZVCPq.png) #### allowJs 允許.ts可以直接import .js ## 修改使用webpack的專案來加入ts [TypeScript專案建立 - 與Webpack JS專案的整合](https://hiskio.com/courses/628/lectures/33124) 1.輸入npm i把範例裝起來 2.輸入npm install --save-dev typescript ts-loader 安裝typescript與ts-loader 3.新增tsconfig.json檔案,並貼上 ``` { "compilerOptions": { "outDir": "./dist/", "noImplicitAny": true, "sourceMap": true, "module": "es6",// es6才有tree-shake功能,也就是只編譯你所用的js功能,如果用的是COMMONJS的話一整包都直接編譯了 "target": "es5", "jsx": "react", "allowJs": true, "moduleResolution": "node" } } ``` 如下圖 ![](https://i.imgur.com/BKmjhfY.png) 4.把scr的index.js修改為index.ts 5.到webpack.congih.js中 把entry: './src/index.js', 修改為entry: './src/index.ts', 把module內的 ``` { test: /\.m?js$/, exclude: /node_modules/, use: { loader: "babel-loader", } } ``` 修改為 ``` { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/, }, ``` 在module同一個層級下增加 ``` resolve: { extensions: ['.tsx', '.ts', '.js'], }, ``` 把devtool: 'source-map' 修改為 devtool: 'inline-source-map', 這樣子sourcemap才會生效 6.移除 npm uninstall @babel/core @babel/preset-env babel-loader 因為已經使用ts-loader取代了 如果一定得使用babel可以參考影片 7.刪除babel.comfig.json ![](https://i.imgur.com/7KcuaqW.png) 8.在scr中的index.ts輸入 ``` let name : string = "Jack"; console.log(name); ``` 9.在終端機輸入npm run dev 按住CTRL點 ![](https://i.imgur.com/AoYjYHP.png) 會出現網頁後按F12出現 ![](https://i.imgur.com/ouUO3Xi.png) 代表環境架設完成