How to Create a VS Code Extension: Let’s Code a Dad Joke Extension in TypeScript



This content originally appeared on Level Up Coding – Medium and was authored by Robin Viktorsson

Photo by Din Djarin on Unsplash

Ever felt like your coding sessions could use a little more pun and a bit less debugging despair? Well, buckle up because we’re about to dive into creating something that’ll make your code and your brain smile: a Dad Joke Extension for VS Code!

Picture this: You’re deep into writing code, you’re squinting at the screen, wondering why your function isn’t returning what you expect. But then — bam! — out of nowhere, your extension pops up with a classic dad joke. Maybe it’s the dad joke you’ve heard a thousand times, but hey, a groan-worthy pun can be just the thing to lift your spirits and get you back on track. And hey, even if you roll your eyes, you’re still smiling.

In this tutorial, we’ll walk through creating a DadJoke++ extension that delivers a new joke every 10 seconds right in your editor, because who doesn’t love a little light-hearted code humor?

Whether you’re a veteran coder, a newbie, or just someone who wants a bit of laughter to spice up your workflow, this extension is for you. And trust us, once you see your jokes popping up, you’ll be coding with a whole new set of dad joke-inspired energy.

So grab your virtual dad hat, put on your punniest thinking cap, and let’s get started on building a dad joke machine inside your VS Code!

Why Create a VS Code Extension? 🧐

In this case, we’ll create an extension just for fun — which is a perfectly valid reason to build one! However, developing a VS Code extension also comes with a range of benefits that can enhance your workflow, boost productivity, and make coding more enjoyable. Here’s why creating your own extension can be incredibly useful:

  • Tailor Your Development Environment: Customizing VS Code to match your specific workflow is one of the top reasons to create an extension. Whether it’s automating tasks, adding custom snippets, or creating new UI elements, extensions allow you to personalize your experience.
  • Boost Productivity: Extensions automate repetitive tasks like code formatting, testing, or deployments, saving you time and reducing errors. You can also integrate external tools or services directly into VS Code, streamlining your workflow.
  • Learn and Improve Your Skills: Creating an extension allows you to gain experience with JavaScript/TypeScript and VS Code’s API. It’s a great way to sharpen your skills while building something useful.
  • Make Coding More Fun: Extensions can inject fun into your coding sessions, like showing random jokes, motivational quotes, or even gamifying your work. Lightening the mood with a dad joke generator or a quirky feature can make a big difference.
  • Help the Community: By solving common problems and sharing your extensions, you contribute to the developer community. Many developers face similar challenges, and your extension could save them time and frustration.
  • Boost Your Personal Brand: Publishing an extension is a great way to showcase your skills and stand out to potential employers. It’s a way to demonstrate your creativity, problem-solving abilities, and involvement in the open-source community.

Creating a VS Code extension can improve your workflow, help others, and have fun while learning new skills. Whether you want to automate tasks, enhance your coding experience, or just add a little humor, building an extension is a rewarding project that can pay off both professionally and personally.

Prerequisites — Everything You Need to Get Started 🥳

Before diving into extension creation, ensure you have the following:

Install Yeoman and VS Code Extension Generator

Yeoman is a scaffolding tool that helps you quickly generate projects based on templates. The generator-code is the template specifically for creating VS Code extensions. Run the following command to install Yeoman and the generator-code:

npm install -g yo generator-code

Let’s Code: Creating the VS Code Extension 👨‍💻

Once the dependencies are installed, you can scaffold your extension using Yeoman. Open a terminal and run the following command:

yo code

This will launch a series of prompts that help you create your extension:

Yeoman provides various options for creating different types of VS Code extensions. In this case, we’ll choose “New Extension (TypeScript)”. Below is a brief overview of each extension type that Yeoman (yo code) can generate:

  • New Extension (JavaScript): Creates a basic VS Code extension using JavaScript. Good for simple functionality like adding commands, UI elements, or modifying the editor’s behavior.
  • New Extension (TypeScript): Similar to the JavaScript extension but written in TypeScript, which offers better type safety and maintainability. Recommended for more complex extensions.
  • New Color Theme: Generates a JSON-based color theme for VS Code. You can customize the UI and syntax highlighting colors to create a unique theme.
  • New Language Support: Adds support for a new programming language in VS Code. Includes syntax highlighting, basic configuration, and optional IntelliSense features.
  • New Code Snippets: Creates a snippet extension that provides predefined code snippets for a specific language. Useful for auto-inserting common code patterns.
  • New Keymap: Generates a keymap extension that customizes or overrides keyboard shortcuts. Useful for replicating keybindings from other editors (e.g., Sublime, Atom, Vim).
  • New Extension Pack: Creates a bundle of multiple extensions into a single package. Useful for distributing a set of related extensions together.
  • New Language Pack (Localization): Provides translations for VS Code’s UI and built-in messages into another language. Helps localize the editor for non-English speakers.
  • New Web Extension (TypeScript): Generates a web-compatible VS Code extension that runs in the browser version of VS Code (e.g., vscode.dev). Works in sandboxed environments without requiring Node.js APIs.
  • New Notebook Renderer (TypeScript): Creates a notebook renderer for VS Code’s interactive notebooks (similar to Jupyter). Used to visualize data from notebook cells in a custom format.

These are our selections:

? What type of extension do you want to create? New Extension (TypeScript)
? What's the name of your extension? DadJoke++
? What's the identifier of your extension? dadjokeplusplus
? What's the description of your extension? Bring some punny joy to your coding sessions with DadJoke++, the ultimate dad joke extension for VS Code! Every time you open a new
file, run a command, or just need a break, DadJoke++ will hit you with a groan-worthy, eye-roll-inducing dad joke straight to your status bar.
? Initialize a git repository? No
? Which bundler to use? esbuild
? Which package manager to use? npm

Since we’re using esbuild, you’ll also need to install the esbuild Problem Matchers VS Code Extension. This is necessary due to some known issues with esbuild and problem matchers references. Once this is done, Yeoman will generate the folder structure for your extension.

Understanding the Generated Folder Structure 🥴

Your extension will have a basic folder structure similar to:

DadJoke--/
├── .vscode/ # VS Code settings for debugging
├── src/ # TypeScript/JavaScript files
│ └── extension.ts # Main extension code
├── esbuild.js # Entry point of esbuild bundler
├── package.json # Metadata and extension settings
├── tsconfig.json # TypeScript configuration (if using TypeScript)
├── README.md # Documentation for your extension
└── more... # Not relevant to explain for now...

The most important files:

  • src/extension.ts: This is where your extension logic resides. This file defines the commands, features, and other behaviors of your extension.
  • package.json: This file contains metadata about your extension, such as name, description, version, commands, contributions to the editor, and dependencies.
  • README.md: This is where you document how to use your extension, which will show in the VS Code Marketplace as well within the Extensions that in VS Code.

Creating the Extension 🛠

Inside the scaffolded project, and within the src/extension.ts file, you'll see a function called activate(), which is executed when the extension is loaded:

import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {
let disposable = vscode.commands.registerCommand('extension.sayHello', () => {
vscode.window.showInformationMessage('Hello World from your first extension!');
});

context.subscriptions.push(disposable);
}

export function deactivate() {}

This code registers a command (extension.sayHello) that displays a popup information message when executed. It also adds the command to the extension’s subscription context, ensuring proper cleanup when the extension is deactivated. You can customize your extension by adding more commands and event listeners in this file.

However, we want to modify this behavior. Instead of displaying a popup with the text “Hello World from your first extension!” in the bottom-right corner of VS Code, we’ll show a dad joke in the status bar (bottom-left corner) every 10 seconds — a less distracting approach.

These are our two main tasks:

  • Fetch a dad joke every 10 seconds from the icanhazdadjoke API (Special thanks to Brett Langdon for maintaining this API).
  • Display the fetched dad joke in the VS Code status bar.

VS Code provides a powerful API that allows you to extend its functionality. In our case, we’ll use the setStatusBarMessage(string text) function from the window object to update the status bar dynamically. Below is the final implementation:

// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';

type DadJokeType = {
id: string;
joke: string;
status: number;
};

async function getDadJoke(): Promise<string> {
try {
const response = await fetch('https://icanhazdadjoke.com/', {
headers: { 'Accept': 'application/json' }
});
const data: DadJokeType = await response.json() as DadJokeType;
return data.joke;
} catch (error) {
return `Woops. Something went wrong: ${error}`;
}
}

// This method is called when your extension is activated
export function activate(context: vscode.ExtensionContext) {
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
const disposable = vscode.commands.registerCommand('dadjokeplusplus.helloWorld', async () => {
// The code you place here will be executed every time your command is executed
// Show the joke in the status bar every 10s

setInterval(async () => {
const joke = await getDadJoke();
vscode.window.setStatusBarMessage(joke);
}, 10000);
});

context.subscriptions.push(disposable);
}

// This method is called when your extension is deactivated
export function deactivate() {}

Debugging the Extension 🔍🐞

To test your extension, VS Code provides a powerful debugging environment. Simply press F5 to launch a new VS Code window, known as the “Extension Development Host.” This window runs your extension just like a regular VS Code extension, allowing you to interact with it seamlessly.

Once the new VS Code window opens, start the extension by opening the Command Palette (Ctrl+Shift+P), searching for DadJoke++, and selecting it. That’s it — your extension is now running!

To debug, set breakpoints in the extension.ts file. You can also view debug logs and output messages by opening the Debug Console with Ctrl+Shift+Y.

Packaging and Publishing Your Extension 📦

1. Prepare for Publishing

Before publishing, ensure that your package.json includes an updated name, displayName, description, publisher, and version. I'm satisfied with what I have.

{
"name": "dadjokeplusplus",
"displayName": "DadJoke++",
"description": "Bring some punny joy to your coding sessions with DadJoke++, the ultimate dad joke extension for VS Code! Every time you open a new file, run a command, or just need a break, DadJoke++ will hit you with a groan-worthy, eye-roll-inducing dad joke straight to your status bar.",
"version": "0.0.1",
"publisher": "RobinViktorsson", // Must match your publisher account id (see Step 4)
"engines": {
"vscode": "^1.98.0"
},
"categories": [
"Other"
],
"activationEvents": [],
"main": "./dist/extension.js",
"contributes": {
"commands": [
{
"command": "dadjokeplusplus.helloWorld",
"title": "DadJoke++"
}
]
},
"scripts": {
"vscode:prepublish": "npm run package",
"compile": "npm run check-types && npm run lint && node esbuild.js",
"watch": "npm-run-all -p watch:*",
"watch:esbuild": "node esbuild.js --watch",
"watch:tsc": "tsc --noEmit --watch --project tsconfig.json",
"package": "npm run check-types && npm run lint && node esbuild.js --production",
"compile-tests": "tsc -p . --outDir out",
"watch-tests": "tsc -p . -w --outDir out",
"pretest": "npm run compile-tests && npm run compile && npm run lint",
"check-types": "tsc --noEmit",
"lint": "eslint src",
"test": "vscode-test"
},
"devDependencies": {
"@types/mocha": "^10.0.10",
"@types/node": "20.x",
"@types/vscode": "^1.98.0",
"@typescript-eslint/eslint-plugin": "^8.25.0",
"@typescript-eslint/parser": "^8.25.0",
"@vscode/test-cli": "^0.0.10",
"@vscode/test-electron": "^2.4.1",
"esbuild": "^0.25.0",
"eslint": "^9.21.0",
"npm-run-all": "^4.1.5",
"typescript": "^5.7.3"
},
"dependencies": {
"node-fetch": "^3.3.2"
}
}

Also, ensure that your README.md provides a clear and concise explanation of the extension. It's also common to include a changelog and usage instructions to help users understand updates and functionality.


# DadJoke++
Introducing **DadJoke++**, the only VS Code extension that delivers **top-tier dad jokes** right to your **status bar** every 10 seconds. Because if your code isn't working, at least your humor should be.

## Change Log

All notable changes to the "dadjoke++" extension will be documented in this file.

### 1.0.0

Initial release of DadJoke++

Last but not least, let’s make sure to include an eye-catching image that represents our VS Code extension on the Visual Studio Marketplace. Simply add the image to the root folder and define its name in the icon property of the package.json file:

{
"name": "dadjokeplusplus",
"displayName": "DadJoke++",
"description": "Bring some punny joy to your coding sessions with DadJoke++, the ultimate dad joke extension for VS Code! Every time you open a new file, run a command, or just need a break, DadJoke++ will hit you with a groan-worthy, eye-roll-inducing dad joke straight to your status bar.",
"version": "0.0.1",
"publisher": "RobinViktorsson",
"icon": "dadjoke.png",
[...] // The rest of the package.json content
}

Step 2: Install vsce

To package and publish your extension, you need the Visual Studio Code Extension Manager (vsce). Install it globally:

npm install -g vsce

Step 3: Package Your Extension

Run this command to create a .vsix file (a VS Code extension package):

vsce package

This will create a .vsix file in your root directory that you can upload to the Visual Studio Code Marketplace.

Step 4: Publish Your Extension

To begin, visit the Visual Studio Marketplace and create a publisher account if you haven’t done so already. Once the publisher account is created, you will see a button to add new extensions. Click it and

This will upload your extension to the VS Code Marketplace, where users can find, install, and use it!

When your Visual Studio Code extension is in the “verifying” status, it means that the extension is undergoing a verification process by the Visual Studio Code Marketplace. This process involves several checks to ensure that the extension meets the Marketplace’s requirements and guidelines.

The verification process can include:

  1. Code Quality Checks: Ensuring that the extension is well-structured, error-free, and does not contain any security vulnerabilities.
  2. Compliance with Guidelines: Verifying that the extension follows the Visual Studio Code Marketplace’s guidelines for content, naming conventions, etc.
  3. Icon and Screenshot Validation: Ensuring the icon and screenshots you provided meet the platform’s image standards.
  4. Automated Testing: Some extensions might undergo automated tests to check if they work properly within Visual Studio Code.
  5. Metadata Validation: Verifying the accuracy of metadata in the package.json file, such as the description, version, and compatibility.

Once the verification process is complete, the status should change, and your extension will either be published or you may be notified if there are issues that need addressing.

If the process takes too long or if you encounter issues, it’s a good idea to check the Visual Studio Code Marketplace’s documentation or contact their support. It usually takes a couple of minutes.

Step 5: Download Your Extension from Visual Studio Marketplace

Search for DadJoke++ in the Extensions view, install it, and once installed, open the Command Palette (Ctrl+Shift+P). Type the extension name, select it, and you’re all set! Sit back, relax, write some code, and enjoy a few classic dad jokes! 👴

Conclusion 📣

Congratulations! You’ve just built and published your very own DadJoke++ extension for VS Code. Now, every coding session comes with a free side of groan-worthy humor, whether you like it or not!

From setting up your development environment to fetching dad jokes in real-time, you’ve walked through the entire process of creating a VS Code extension. And who knows? Maybe this is just the beginning — today it’s dad jokes, tomorrow it’s an AI-powered debugging assistant (that still cracks puns, of course).

So keep building, keep experimenting, and most importantly — keep laughing. After all, coding should be fun, and if a corny joke can make a frustrating bug a little more bearable, then mission accomplished! 🎉

Now go forth and spread the dad joke joy — one pun at a time.

🙏 Thanks for reading to the end! If you have any questions, feel free to drop a comment below.

If you enjoyed this article, follow me on social media — I’d love to connect and follow you back:

And don’t forget to follow Level Up Coding for more insightful content! 🚀


How to Create a VS Code Extension: Let’s Code a Dad Joke Extension in TypeScript👨 was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding – Medium and was authored by Robin Viktorsson