Chrome Extensions using Vite + Typescript + React: Stepwise Process
Tags: javascript, javascripttips, vitejs, chromeextension
Published: 2023-11-03 14:46:54

---
title: Chrome Extensions using Vite + Typescript + React: Stepwise Process
published: true
date: 2023-10-24 02:32:35 UTC
tags: javascript,javascripttips,vitejs,chromeextension
canonical_url: 
---

Chrome extensions come in really handy when it comes to blocking ads, improving productivity, managing cluttered tabs, and of course improving the readability of code on GitHub for developers.❤️

![](https://cdn-images-1.medium.com/max/1024/0*sWqccE_AfTucc7Z8.png)
_Image Courtesy: singlequote.blog_

In this blog, let’s create a Chrome extension in an easy 4-step process using [React](https://react.dev/), [Typescript](https://www.typescriptlang.org/), and [Vite bundler](https://vitejs.dev/guide/why.html).

Let us assume that nodejs is pre-installed, if not then you can follow this [setup nodejs and dependencies on the development/local machine](https://singlequote.blog/chrome-extension-using-node-rollup-plugin-stepwise-process/(opens%20in%20a%20new%20tab)).

Now, since we are all set, Let’s begin!!

### Step 1: Initialise a new Project

Create a new project using Vite.

```
npm create vite@latest
```

This command will prompt for a few inputs from the user:

1. **Project Name:** Project name that you want to give to your project.
2. **Select a Framework:** Choose ‘React’ as that is what we are going with in this tutorial.
3. **Select a variant** : Choose ‘Typescript’ there to keep up with this tutorial.

![](https://cdn-images-1.medium.com/max/558/0*Tx52vye-FcK2X1aM.png)
_Image Courtesy: singlequote.blog_

### Step 2: Install Dependencies & Run Application on Local

Now change the directory to the created/initialized folder and install the dependencies.

```
> cd vite-ts-react-test
> npm install
```

Now to test if everything worked fine. Run the following command in the terminal.

```
npm run dev
```

This will prompt a new message on the command line similar to below screenshot:

![](https://cdn-images-1.medium.com/max/684/0*UCdwuiNdCVvVxbaF.png)
_Image Courtesy: singlequote.blog_

This signifies that everything is running fine up to this point. Once you open the above shown — [http://localhost:5173/](http://localhost:5173/) on the browser, you will a see Vite welcome page, something like this:

![](https://cdn-images-1.medium.com/max/918/0*U_PnruXEZpWBnkim.png)
_Image Courtesy: singlequote.blog_

Next exit from the vite localhost prompt using ‘CTRL+C’ and run the command to build the project

```
npm run build
```

![](https://cdn-images-1.medium.com/max/924/0*nnZ1RvP6rQTkmj5I.png)
_Image Courtesy: singlequote.blog_

An output something like the above will come up on the terminal/cmd.

### Step 3: Create a Chrome Extension and Validate it

At the end of step 2, the boilerplate will be ready inside the project directory. You will see a lot of stuff inside the directory but don’t worry we are only interested in a few of these:

1. **Dist:** The “_build_” command creates this folder dynamically by copying a few files from other folders or as instructed in the config file. For this tutorial default configuration will work. So, we are not going to touch anything inside it.
2. **Public:** We will add all of our project files and static files in this folder and the “_build_” command will add those to the dist folder, once the build is successful.
3. **Src:** This is where magic happens. This is where we write typescript code, you will also some typescript written in this blog.

![](https://cdn-images-1.medium.com/max/451/0*0OKcuFLdYTYhRPp4.png)
_Image Courtesy: singlequote.blog_

Now go to **_public_** folder and create a new file **_manifest.json_** :

```
{
    "manifest_version": 3,
    "name": "vite-ts-react-test",
    "version": "1.0",
    "description": "",
    "action": {
        "default_popup": "index.html"
    },
    "permissions": [
        "scripting",
        "tabs",
        "activeTab"
    ],
    "host_permissions": [
        "https://*/*",
        "http://*/*"
    ],
    "icons": {
        "16": "images/16x16.png",
        "32": "images/32x32.png"
    }
  }
```

Run the below command to build the project:

```
npm run build
```

Now go to chrome://extension, and enable developer mode if not already set. Click on “Load Unpacked” to pick **_dist_** folder from the local file system.

Voila!! Our Chrome Extension is ready to try.

If you are still following up to this point, then a new extension will be available on your extension list. You can go ahead and click on the extension on the Chrome menu bar, you will see the Vite welcome page as mentioned [above on this page](https://singlequote.blog/chrome-extension-using-vite-typescript-react-stepwise-process/#Vite-Welcome-page-singlequoteblog).

### Step 4: Scripting in Chrome Extension

In this step, let’s try to do some scripting to see if it works. Let’s go to the _“src”_ folder to write some typescript code.

In this script, we will write a code using Chrome API to change the background color of the web page.

let’s install the Chrome API using the below command:

```
npm install -D @types/chrome
```

Now look for src/App.tsx file in the project directory and change the code as below:

```
// import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'

function App() {
  // const [count, setCount] = useState(0) 
  const onClick = async () => {
    let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    chrome.scripting.executeScript({
      target: { tabId: tab.id! },
      func: () => {
        document.body.style.backgroundColor = 'green';
      }
    });
  }
  return (
    <>
      <div>
        <a href="https://vitejs.dev" target="_blank">
          <img src={viteLogo} className="logo" alt="Vite logo" />
        </a>
        <a href="https://react.dev" target="_blank">
          <img src={reactLogo} className="logo react" alt="React logo" />
        </a>
      </div>
      <h1>Vite + React</h1>
      <div className="card">
        <button onClick={() => changeColorOnClick()}>
         Change Color
        </button>
        <p>
          Edit <code>src/App.tsx</code> and save to test HMR
        </p>
      </div>
      <p className="read-the-docs">
        Click on the Vite and React logos to learn more
      </p>
    </>
  )
}
export default App
```

if you look closely most of the code is already available. The only new addition is a function “ **_changeColorOnClick_** “.

```
const changeColorOnClick = async () => {
    let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    chrome.scripting.executeScript({
      target: { tabId: tab.id! },
      func: () => {
        document.body.style.backgroundColor = 'green';
      }
    });
  }
```

Now don’t forget to build it again and refresh the extension from chrome://extensions.

```
npm run build
```

and it’s done!!

Give it a try by visiting any website with a considerably white background like [singlequote.blog](http://singlequote.blog/).

![](https://cdn-images-1.medium.com/max/600/0*yfNDERWCqPu6OJa8.gif)

**Tips and Tricks** : Running the **_build_** command after every change could be tiresome and error-prone. If you forgot to refresh and are wondering why the changes are not coming up — Rollup is here to rescue us. Read about [Chrome Extension using Node + Rollup plugin: Stepwise Process](https://singlequote.blog/chrome-extension-using-node-rollup-plugin-stepwise-process/(opens%20in%20a%20new%20tab)).