Building a Chrome Extension with React and Plasmo: A Step-by-Step Guide

Are you looking to build a Chrome extension using React? Look no further than Plasmo, a framework that makes it easy to build extensions with React. In this article, we’ll walk you through the process of building a Chrome extension with Plasmo, from initializing a new project to adding local storage support.

Getting Started with Plasmo

To get started with Plasmo, you’ll need to initialize a new project. You can do this by running the following command in your terminal:

npx plasmo init my-extension

This will create a new directory called my-extension with the basic structure for a Plasmo project.

Setting up Tailwind CSS

Next, you’ll want to set up Tailwind CSS to handle styling for your extension. To do this, you’ll need to install the following dependencies:

npm install tailwindcss postcss autoprefixer

Then, run the following command to generate the tailwind.config.js and postcss.config.js files:

npx tailwindcss init -p

Building the Frontend

With Tailwind CSS set up, you can start building the frontend of your extension. Create a new file called Container.tsx in the src/components/layouts directory:

import React from 'react';

const Container = () => {
return (
<div>
<h1>Welcome to my extension!</h1>
</div>
);
};

export default Container;
<code>
Then, create a new file called `main.tsx` in the `src` directory:
</code>jsx
import React from 'react';
import Container from './components/layouts/Container';

const App = () =&gt; {
return (
<h2>This is the main content area.</h2>
);
};

export default App;

Adding Logic

Next, you’ll want to add some logic to your extension. For example, you might want to add a button that saves some data to local storage. To do this, you’ll need to create a new function that handles the button click event:

import React, { useState } from 'react';

const App = () =&gt; {
const [data, setData] = useState('');

const handleSubmit = (event) =&gt; {
event.preventDefault();
// Save data to local storage here
};

return (
<h2>This is the main content area.</h2>
<form></form><input type="text" value="{data}" />
<button type="submit">Save</button>

);
};

Adding Local Storage Support

Finally, you’ll want to add local storage support to your extension. To do this, you’ll need to install the @plasmohq/storage package:

npm install @plasmohq/storage

Then, you can use the storage API to save data to local storage:

import { storage } from '@plasmohq/storage';

const handleSubmit = (event) =&gt; {
event.preventDefault();
storage.set('data', data);
};

That’s it! With these steps, you should be able to build a basic Chrome extension using React and Plasmo. Of course, there are many more features you can add to make your extension more powerful.

Leave a Reply