[英]Visual Studio Code compile on save
如何配置 Visual Studio Code 以在保存時編譯 typescript 文件?
我看到可以配置任務以使用${file}
作為參數來構建焦點文件。 但我希望在保存文件時完成此操作。
自 2018 年 5 月起,您不再需要手動創建tsconfig.json
或配置任務運行器。
tsc --init
以創建tsconfig.json
文件(如果您還沒有)。tsc: watch - tsconfig.json
。 如果需要,您可以在工作區中擁有多個tsconfig.json
文件並一次運行多個編譯(例如前端和后端分開)。
您可以使用構建命令執行此操作:
使用"watch": true
創建一個簡單的tsconfig.json
(這將指示編譯器監視所有已編譯的文件):
{
"compilerOptions": {
"target": "es5",
"out": "js/script.js",
"watch": true
}
}
注意files
數組被省略,默認情況下所有子目錄中的所有*.ts
文件都會被編譯。 您可以提供任何其他參數或更改target
/ out
,只需確保將watch
設置為true
。
配置您的任務( Ctrl+Shift+P -> Configure Task Runner
):
{
"version": "0.1.0",
"command": "tsc",
"showOutput": "silent",
"isShellCommand": true,
"problemMatcher": "$tsc"
}
現在按Ctrl+Shift+B構建項目。 您將在輸出窗口 ( Ctrl+Shift+U ) 中看到編譯器輸出。
保存時編譯器會自動編譯文件。 要停止編譯,請按Ctrl+P -> > Tasks: Terminate Running Task
我專門為這個答案創建了一個項目模板: typescript-node-basic
如果您想避免必須使用CTRL
+ SHIFT
+ B
而是希望在保存文件時發生這種情況,您可以將命令綁定到與保存操作相同的快捷方式:
[
{
"key": "ctrl+s",
"command": "workbench.action.tasks.build"
}
]
這在您的 keybindings.json 中 - (使用 File -> Preferences -> Keyboard Shortcuts 前往此位置)。
如果按Ctrl + Shift + B看起來很費力,您可以打開“自動保存”(文件 > 自動保存)並使用 NodeJS 監視項目中的所有文件,並自動運行 TSC。
打開 Node.JS 命令提示符,將目錄更改為您的項目根文件夾並鍵入以下內容;
tsc -w
嘿 presto,每次 VS Code 自動保存文件時,TSC 都會重新編譯它。
博客文章中提到了這種技術;
http://www.typescriptguy.com/getting-started/angularjs-typescript/
向下滾動到“保存時編譯”
寫一個擴展
現在 vscode 是可擴展的,可以通過擴展來掛鈎 on save 事件。 可以在此處找到為 VSCode 編寫擴展的一個很好的概述: https ://code.visualstudio.com/docs/extensions/overview
這是一個簡單的示例,它只調用echo $filepath
並在消息對話框中輸出標准輸出:
import * as vscode from 'vscode';
import {exec} from 'child_process';
export function activate(context: vscode.ExtensionContext) {
vscode.window.showInformationMessage('Run command on save enabled.');
var cmd = vscode.commands.registerCommand('extension.executeOnSave', () => {
var onSave = vscode.workspace.onDidSaveTextDocument((e: vscode.TextDocument) => {
// execute some child process on save
var child = exec('echo ' + e.fileName);
child.stdout.on('data', (data) => {
vscode.window.showInformationMessage(data);
});
});
context.subscriptions.push(onSave);
});
context.subscriptions.push(cmd);
}
(也引用了這個 SO 問題: https ://stackoverflow.com/a/33843805/20489)
現有的 VSCode 擴展
如果你只想安裝一個現有的擴展,這是我在 VSCode 庫中寫的一個: https ://marketplace.visualstudio.com/items/emeraldwalk.RunOnSave
源代碼可在此處獲得: https ://github.com/emeraldwalk/vscode-runonsave/blob/master/src/extension.ts
保存時自動編譯的一種極其簡單的方法是在終端中鍵入以下內容之一:
tsc main --watch // autosave `main.ts`
tsc -w // autosave all typescript files in your project
請注意,這只會在此終端打開時運行,但這是一個非常簡單的解決方案,可以在您編輯程序時運行。
我建議不要構建單個文件並綁定 Ctrl+S 來觸發該構建,而是使用以下 tasks.json 文件以監視模式啟動 tsc:
{
"version": "0.1.0",
"command": "tsc",
"isShellCommand": true,
"args": ["-w", "-p", "."],
"showOutput": "silent",
"isWatching": true,
"problemMatcher": "$tsc-watch"
}
這將構建整個項目,然后重新構建保存的文件,而與它們的保存方式無關(Ctrl+S,自動保存,...)
在你的tsconfig.json
"compileOnSave": true, // change it to true and save the application
如果問題仍然存在,則應用step-2
重啟你的編輯器
如果問題仍未解決,則應用step-3
更改任何路線,將其還原並保存應用程序。 它將開始編譯。 IE
const routes: Routes = [
{
path: '', // i.e. remove , (comma) and then insert it and save, it'll start compiling
component: MyComponent
}
]
我使用gulp-typescript和增量構建使用 gulp 任務實現了保存時編譯。 這允許您隨意控制編譯。 注意我的變量 tsServerProject,在我的真實項目中,我也有 tsClientProject,因為我想編譯我的客戶端代碼而不指定模塊。 據我所知,你不能用 vs 代碼來做到這一點。
var gulp = require('gulp'),
ts = require('gulp-typescript'),
sourcemaps = require('gulp-sourcemaps');
var tsServerProject = ts.createProject({
declarationFiles: false,
noExternalResolve: false,
module: 'commonjs',
target: 'ES5'
});
var srcServer = 'src/server/**/*.ts'
gulp.task('watch-server', ['compile-server'], watchServer);
gulp.task('compile-server', compileServer);
function watchServer(params) {
gulp.watch(srcServer, ['compile-server']);
}
function compileServer(params) {
var tsResult = gulp.src(srcServer)
.pipe(sourcemaps.init())
.pipe(ts(tsServerProject));
return tsResult.js
.pipe(sourcemaps.write('./source-maps'))
.pipe(gulp.dest('src/server/'));
}
選擇Preferences -> Workspace Settings並添加以下代碼,如果您啟用了 Hot reload,則更改會立即反映在瀏覽器中
{
"files.exclude": {
"**/.git": true,
"**/.DS_Store": true,
"**/*.js.map": true,
"**/*.js": {"when": "$(basename).ts"}
},
"files.autoSave": "afterDelay",
"files.autoSaveDelay": 1000
}
我可以說,使用最新版本的 TypeScript 1.8.X 和 Visual Studio 代碼 1.0,我展示的技術已經過時了。 只需在項目的根級別使用 tsconfig.json 即可自動進行語法檢查。 然后在命令行上使用 tsc -w 自動觀看/重新編譯。 它將讀取相同的 tsconfig.json 文件以獲取 ts 編譯的選項和配置。
// tsconfig.json
{
"compilerOptions": {
"module": "amd",
"target": "ES5",
"noImplicitAny": false,
"removeComments": true,
"preserveConstEnums": true,
"inlineSourceMap": true
},
"exclude": [ "node_modules" ]
}
我使用在 .vscode/tasks.json 的文件夾上運行的自動任務(應該工作 VSCode >=1.30)
{
"version": "2.0.0",
"tasks": [
{
"type": "typescript",
"tsconfig": "tsconfig.json",
"option": "watch",
"presentation": {
"echo": true,
"reveal": "silent",
"focus": false,
"panel": "shared"
},
"isBackground": true,
"runOptions": {"runOn": "folderOpen"},
"problemMatcher": [
"$tsc-watch"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
如果這仍然無法在項目文件夾中打開,請嘗試 Ctrl+shift+P 和任務:管理文件夾中的自動任務,然后在主項目文件夾或正在運行的文件夾中選擇“允許文件夾中的自動任務”。
您需要增加手表限制以修復保存時重新編譯的問題,打開終端並輸入以下兩個命令:
sudo sysctl fs.inotify.max_user_watches=524288
sudo sysctl -p --system
要使更改在重新啟動后仍然存在,請同時運行以下命令:
echo fs.inotify.max_user_watches=524288 | sudo tee /etc/sysctl.d/40-max-user-watches.conf && sudo sysctl --system
嘗試了上述方法,但由於要觀看的最大文件已超過限制,我在感覺喜歡時停止了自動編譯。
運行cat /proc/sys/fs/inotify/max_user_watches
命令。
如果它顯示的文件數較少,包括 node_modules 則以 root 權限打開文件/etc/sysctl.conf
並附加
fs.inotify.max_user_watches=524288
進入文件並保存
再次運行 cat 命令以查看結果。 它會起作用的! 希望!
這里有各種有效的答案,但不一定對每個不同的 TS 編譯器環境的每個人都有好處。 也許跟隨可以在全球范圍內工作。
在項目根文件夾下有一個最小的tsconfig.json
,例如,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/",
"forceConsistentCasingInFileNames": true,
"sourceMap": true,
"strict": true,
"target": "es2017",
"module": "es2020",
}
# where you can set your outDir accordingly.
設置您當前的 TS 編譯器tsc
以查看項目根文件夾。 為此,請打開另一個終端選項卡,然后運行以下命令並將其保留在后台。
$ tsc --watch --project ./
# tsc is your working compiler, may be different than this. I currently using global TyperScript Compiler to watch on save therefore tcs. Change to yours accordingly
# ref: https://www.typescriptlang.org/docs/handbook/compiler-options.html
這比依賴 IDE 任務觀察器更簡潔。
當您不再需要觀看時,只需 Ctrl/Command + C 即可終止它,甚至關閉/回收終端
在項目文件夾中運行 tsc --init 以創建 tsconfig。 json 文件(如果您還沒有)
按 Ctrl+Shift+B 在 VS Code 中打開任務列表並選擇“tsc: watch - tsconfig.json”
完畢! 每次保存文件時都會重新編譯您的項目。
這對我有用,但對於第 2 步,我只能在任務列表中選擇“tsc: espion - tsconfig.json”(在列表中找不到“tsc: watch - tsconfig.json”)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.