πŸš€ OharaLumina

Visual Studio Code compile on save

Visual Studio Code compile on save

πŸ“… | πŸ“‚ Category: Typescript

In the fast-paced world of software development, every second counts. Developers constantly seek tools and workflows that streamline their process, enhance productivity, and minimize friction. One such powerful feature, often underutilized, is the ability to enable Visual Studio Code compile on save. This capability fundamentally transforms how code is built and tested, moving from manual compilation steps to an automated, instantaneous feedback loop. By automatically compiling or transpiling your code the moment you save a file, you can catch errors earlier, see changes reflected faster, and maintain a state of flow that is crucial for complex problem-solving. Embracing this efficient approach is not just a convenience; it’s a strategic enhancement to any modern developer’s toolkit, significantly reducing context switching and improving overall development velocity.

Understanding “Compile on Save”: What It Is and Why It Matters

Compile on save refers to the automatic execution of a compilation or transpilation process every time a source file is saved within your integrated development environment (IDE). For languages like TypeScript, Sass, or even frameworks that require pre-processing (like React with JSX), this means your human-readable code is instantly converted into the format required for execution – JavaScript, CSS, or bundled assets – without needing a separate command. This immediate feedback loop is invaluable, as it allows developers to identify syntax errors, type mismatches, or style issues the moment they occur, rather than later in the build cycle.

This automated approach significantly enhances the developer workflow. Instead of manually running a compiler or waiting for a lengthy build process, the changes are processed in the background, making development feel more seamless and responsive. For example, a front-end developer working with Sass can see their CSS updates reflected almost instantly in the browser, especially when combined with live reloading tools. This immediate visual confirmation helps in rapid iteration and reduces the time spent debugging styling issues. It’s a key component of modern build automation that accelerates development cycles.

For developers looking to maximize efficiency, Visual Studio Code compile on save capabilities streamline the development process by automatically building or transpiling code immediately upon file save, thus providing instant feedback on errors and ensuring that the executable code is always up-to-date with the latest changes without manual intervention. This immediate feedback loop is crucial for catching errors early and maintaining a productive rhythm, especially with languages that require a compilation step before execution.

Configuring Compile on Save in VS Code

Setting up compile on save in Visual Studio Code often involves configuring tasks. VS Code’s task runner system is incredibly flexible, allowing you to integrate external tools like TypeScript’s tsc --watch, Sass compilers, or build tools like Gulp and Webpack. The core concept revolves around defining a “watch” task that monitors your source files for changes and then triggers the compilation command. This eliminates the need to constantly switch to your terminal and manually execute build commands after every modification.

For TypeScript, a common pattern is to use the built-in TypeScript compiler. If you have a tsconfig.json file in your project, VS Code can automatically detect and suggest a TypeScript watch task. For other languages or custom build steps, you’ll typically create a tasks.json file within your project’s .vscode directory. This file defines the commands that should run. According to a survey by Stack Overflow, developers spend approximately 10-20% of their time on debugging and build-related issues, a figure that can be significantly reduced with proper build automation.

Here’s a general guide to setting up a compile on save task:

  1. Open the Command Palette: Press Ctrl+Shift+P (Windows/Linux) or Cmd+Shift+P (macOS).
  2. Select “Tasks: Configure Task” or “Tasks: Configure Default Build Task”: This will prompt you to select a task runner template or create a tasks.json file.
  3. Choose a Template or Create a Custom Task: For TypeScript, select “TypeScript - Watch”. For others, choose “Others” to create an empty template.
  4. Define Your Task in tasks.json: ``` { “version”: “2.0.0”, “tasks”: [ { “label”: “watchSass”, “type”: “shell”, “command”: “sass –watch src/styles.scss:dist/styles.css”, “group”: { “kind”: “build”, “isDefault”: true }, “problemMatcher”: [], “isBackground”: true, “presentation”: { “reveal”: “never” } } ] }
    
     This example sets up a basic Sass watch task. The `"isBackground": true` property is crucial for a watch task, as it tells VS Code the task runs continuously in the background.
    
  5. Start the Watch Task: Go back to the Command Palette and select “Tasks: Run Build Task” or “Tasks: Run Task” and choose your defined watch task (e.g., “watchSass”).
  6. Set as Default (Optional): If you want this task to run automatically when you open the folder, you can set it as the default build task via “Tasks: Configure Default Build Task”.

Advanced Compile on Save Techniques & Best Practices

Beyond basic language-specific watch modes, advanced Visual Studio Code compile on save configurations can deeply integrate with more complex build pipelines. For projects using build tools like Webpack, Rollup, or Gulp, you can configure VS Code tasks to trigger these tools in watch mode. This allows for sophisticated bundling, minification, and asset processing to occur automatically upon saving, further enhancing developer productivity. Integrating with a task runner means your entire build chain can respond to file changes, not just individual compilation steps.

One powerful technique is leveraging hot module replacement (HMR) or hot reloading, especially in conjunction with front-end frameworks. When your VS Code auto-compile task updates a module, HMR can inject those changes into a running application without a full page refresh, preserving the application’s state. This dramatically speeds up UI development and provides an incredibly smooth developer experience. For instance, a React developer using Create React App already benefits from Question & Answer :

How can I configure Visual Studio Code to compile typescript files on save?

I see it is possible to configure a task to build the file in focus using the ${file} as an argument. But I would like this to be done when a file is saved.

May 2018 update:

As of May 2018 you no longer need to create tsconfig.json manually or configure task runner.

  1. Run tsc --init in your project folder to create tsconfig.json file (if you don’t have one already).
  2. Press Ctrl+Shift+B to open a list of tasks in VS Code and select tsc: watch - tsconfig.json.
  3. Done! Your project is recompiled on every file save.

You can have several tsconfig.json files in your workspace and run multiple compilations at once if you want (e.g. frontend and backend separately).

Original answer:

You can do this with Build commands:

Create a simple tsconfig.json with "watch": true (this will instruct compiler to watch all compiled files):

{ "compilerOptions": { "target": "es5", "out": "js/script.js", "watch": true } } 

Note that files array is omitted, by default all *.ts files in all subdirectories will be compiled. You can provide any other parameters or change target/out, just make sure that watch is set to true.

Configure your task (Ctrl+Shift+P -> Configure Task Runner):

{ "version": "0.1.0", "command": "tsc", "showOutput": "silent", "isShellCommand": true, "problemMatcher": "$tsc" } 

Now press Ctrl+Shift+B to build the project. You will see compiler output in the output window (Ctrl+Shift+U).

The compiler will compile files automatically when saved. To stop the compilation, press Ctrl+P -> > Tasks: Terminate Running Task

I’ve created a project template specifically for this answer: typescript-node-basic

🏷️ Tags: