Introduction
Creating a custom webview for a VS Code extension can significantly enhance your development experience. This guide will walk you through building a VS Code extension webview using Vue for the UI, Vite for efficient frontend builds, and Tailwind CSS for styling, all while ensuring a native VS Code look and feel.
Prerequisites
Before you begin, ensure you have Node.js and npm installed. Additionally, install the VS Code extension generator with:
npm install --global yo generator-code
You should also have VS Code installed on your system.
Setting Up the Extension
Start by creating the basic structure of your extension with the following command:
yo code
Choose to create a new TypeScript extension named vue-webview-vite and initialize a Git repository. This will set up the necessary files and folders, such as package.json, src/extension.ts, and tsconfig.json.
Running the Initial Extension
Open src/extension.ts in VS Code and press F5 to launch the extension in a new window. Use the Command Palette (Ctrl + Shift + P or Cmd + Shift + P on macOS) to run Hello World, confirming the extension is ready for further development.
Integrating Vue with Vite
From the extension root, create a Vue app with Vite:
npm create vite@latest webview-ui
Select Vue and TypeScript as your framework and variant respectively. Navigate into the webview-ui directory and install the necessary dependencies:
cd webview-ui
npm install
Adding Tailwind CSS
While inside webview-ui, install Tailwind CSS using the Vite plugin:
npm install tailwindcss @tailwindcss/vite
Update the vite.config.ts and style.css files to incorporate Tailwind CSS while maintaining compatibility with VS Code theme variables.
Building VS Code-Themed Components
Develop Vue components styled with Tailwind CSS and VS Code theme variables. Create reusable components like VSCodeButton.vue, VSCodeTextField.vue, and VSCodeCard.vue to enhance your webview's UI.
Implementing VS Code API Messaging
To enable communication between the webview and VS Code, create a message-passing system using a TypeScript wrapper in vscode-api.ts. This allows the Vue app to send and receive messages via the VS Code API.
Finalizing the Vue Webview UI
Integrate the Vue components within Webview.vue, ensuring they communicate effectively with the VS Code extension. Use App.vue to render Webview.vue, keeping the main logic organized.
Building and Running the Extension
Compile the Vue app using:
npm run build
Ensure that all necessary files are included in the build. Register the webview command in package.json, and configure extension.ts to create the webview panel using VS Code's API.
Development Workflow
Utilize concurrently to run both the TypeScript and Vite watchers simultaneously. Add scripts to package.json and start the development process with:
npm run dev