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:
“`jsx
import React from ‘react’;
const Container = () => {
return (
Welcome to my extension!
);
};
export default Container;
jsx
Then, create a new file called `main.tsx` in the `src` directory:
import React from ‘react’;
import Container from ‘./components/layouts/Container’;
const App = () => {
return (
This is the main content area.
);
};
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:
“`jsx
import React, { useState } from ‘react’;
const App = () => {
const [data, setData] = useState(”);
const handleSubmit = (event) => {
event.preventDefault();
// Save data to local storage here
};
return (
This is the main content area.
);
};
“`
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:
“`jsx
import { storage } from ‘@plasmohq/storage’;
const handleSubmit = (event) => {
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.