# 產生TypeScript的declare檔案 ### 透過Node.js :::success 使用VS Code開啟專案資料夾,輸入指令建立Node.js專案 ``` npm init -y ``` 此指令會建立 `package.json`檔案,為JavaScript的套件設定檔 ::: :::success 設定npm run build的欄位,修改 `package.json`的`scripts`欄位 ``` "scripts": { "build": "tsc -d", "start-dev": "npm run build -- --watch", "test": "echo \"Error: no test specified\" && exit 1" } ``` ::: :::success 安裝typescript套件 ``` npm i -D typescript ``` -D參數即--save-dev參數,表示此套件只使用在這個專案 ::: :::success 建立TypeScript的設定檔: `tsconfig.json` ``` tsc --init ``` 修改內容,指定要編譯的檔案(若不設定files,專案內所有檔案都會產出.d.ts) ``` { "compilerOptions": { "target": "ES6" }, "files": [ "index.ts" ] } ``` ::: :::success 執行編譯,即可產出declaration files(.d.ts) ``` npm run build ``` PS. 就算編譯失敗(ex: 找不到引用檔,型別錯誤..),仍然會產出檔案 ::: ### VSCode內F5一鍵執行 完成以上環境設定後,進到Run的設定,點選齒輪產生 `launch.json` 設定檔  改為以下內容即可 ``` "configurations": [ { "type": "node-terminal", "name": "Run Script: build", "request": "launch", "command": "npm run build", "cwd": "${workspaceFolder}" } ] ``` 參考來源: 1.[在Node.js專案中使用TypeScript](https://magiclen.org/typescript-nodejs/) --- ### 純 command 執行 * 首次安裝 :::success 透過 npm 安裝 typescript ``` npm install -g typescript ``` 啟動 compiler ``` npx tsc ``` ::: * 使用方法 :::success 從 ts 產生, 並且移除註解 ``` tsc 檔名.ts -d --removecomments ``` 從 js 產生 ``` tsc 檔名.js -d --allowjs ``` ::: :::warning 由於從 js 會產生相同檔名的 js 而出現寫入錯誤 (TS5055) 可以另外指定輸出檔名或資料夾 ``` --outfile 輸出檔名.js ``` ``` --outdir 輸出資料夾 ``` ::: :::info 目前無法忽略 protected 和 private 要自行手動移除不需要對外公開的方法或屬性 ::: [參考來源](https://stackoverflow.com/questions/62366510/tsc-declaration-how-to-hide-private-methods-and-attributes) --- ### 透過 Visual Studio 產生 :::info 1. 透過 External Tools 的功能來執行 tsc 2. 會抓取目前正在使用中的檔案路徑 3. 如果要輸出檔案到不同路徑, 需要使用 tsc 的 **--outDir** :::  :::info 參數用途 * /k * 後面可執行 command * $(ItemPath) * 抓取目前正在使用中的檔案路徑 * $(ItemDir) * cmd 的目錄切換到目前的檔案資料夾 (非必要) ::: 參考文件 [Managing External Tools](https://docs.microsoft.com/en-us/visualstudio/ide/managing-external-tools) [Developer Command Prompt for Visual Studio](https://docs.microsoft.com/sr-latn-rs/dotnet/framework/tools/developer-command-prompt-for-vs) --- ###### tags: `Node.js` `Declaration Files`
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.