如何为VSCode的Node.js网站启动配置创建Restart Config?
Great question! You have a couple of solid options to add restart capabilities—either auto-restart when files change (super useful during development) or a manual restart command. Let’s break them down:
Option 1: Auto-Restart on File Changes (Recommended)
The easiest way to get auto-restart is using nodemon, a tool that watches for file changes and restarts your Node.js app automatically. Here’s how to set it up with your VS Code launch config:
First, install
nodemonas a development dependency:npm install --save-dev nodemonUpdate your
.vscode/launch.jsonwith a new configuration that usesnodemon:{ "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launch Program", "program": "${workspaceFolder}\\main.js" }, { "type": "node", "request": "launch", "name": "Launch with Auto-Restart", "runtimeExecutable": "nodemon", "program": "${workspaceFolder}\\main.js", "restart": true, "console": "integratedTerminal", "internalConsoleOptions": "neverOpen" } ] }runtimeExecutable: Tells VS Code to usenodemoninstead of the regularnodecommand.restart: Enables auto-restart whenever files are modified.console: Uses the integrated terminal so you can see the app’s output clearly.
Now, when you select "Launch with Auto-Restart" from the debug dropdown, your app will automatically restart every time you save changes to your code.
Option 2: Manual Restart Script
If you prefer a manual restart command (e.g., to run via the terminal or a VS Code task), you can add an npm script to your package.json:
Open your
package.jsonand add these scripts:{ "scripts": { "start": "node main.js", "restart": "npm run stop && npm start", "stop": "pkill -f 'node main.js' || true" } }- Note: The
stopcommand usespkillwhich works on macOS/Linux. For Windows, replace thestopscript with:"stop": "taskkill /F /IM node.exe /T || true"
- Note: The
Now you can run
npm run restartin your terminal to stop the current app instance and start it fresh.
Bonus: VS Code Debug Toolbar Restart
Don’t forget that when you’re already running your app in debug mode (using your original "Launch Program" config), you can click the Restart button (circular arrow) in the VS Code debug toolbar to instantly restart the session without needing any extra configs.
内容的提问来源于stack exchange,提问作者Messivert

