Preact

Preact is a fast, lightweight alternative to React with the same modern API.

Extension.js offers built-in support for Preact and JSX. To use Preact in your extension, ensure that Preact is added as a dependency or devDependency in your package.json. Once added, you're ready to build your extension with Preact!

Starter Preact Template

Extension.js includes a New Tab Preact template, which is ideal for creating extensions with a new tab page built using Preact. This template allows you to get started quickly with Preact's lightweight approach.

Preact Extension Template

Try it yourself

npm
pnpm
yarn
npx extension@latest create my-extension --template=new-preact

Preact + Content Script Template

Alternatively, Extension.js supports a Content Script Preact template, allowing you to inject Preact components into web pages through content scripts. This is useful when your extension interacts with existing web pages.

Preact + Content Script Template

Try it yourself

npm
pnpm
yarn
npx extension@latest create my-extension --template=content-preact

Usage With an Existing Extension

To integrate Preact into an existing extension, follow these steps:

Installation

Install the required dependencies:

npm
yarn
pnpm
bun
npm install preact preact/hooks @types/preact --save-dev

Configuration

Extension.js expects Preact files to use the following file extensions:

  • If TypeScript is not enabled: *.jsx
  • If TypeScript is enabled: *.tsx

Usage Examples

In a New Tab Extension

To use Preact in a new tab extension, include it as a <script> in your HTML file:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>New Extension</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this extension.</noscript>
    <div id="root"></div>
  </body>
  <script src="./Index.jsx"></script>
</html>
// Index.jsx;
import { h, render } from "preact";
import MyExtension from "./MyExtension";

const root = document.getElementById("root");

render(<MyExtension />, root);
// MyExtension.jsx;
export default function MyExtension() {
  return <h1>Hello, Preact Extension!</h1>;
}

In a content_script File

For content scripts, you can inject Preact into the page by dynamically creating an HTML element and rendering Preact into it:

import { h, render } from "preact";
import MyExtension from "./MyExtension";

// Dynamically import styles for content scripts
import("./content.css");

setTimeout(initial, 1000);

function initial() {
  // Create a new div element and append it to the document body
  const rootDiv = document.createElement("div");
  rootDiv.id = "extension-root";
  document.body.appendChild(rootDiv);

  // Render the <MyExtension /> component
  render(<MyExtension />, rootDiv);
}

Next Steps