chrome-extension-wxt

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Chrome Extension Development with WXT

基于WXT框架的Chrome扩展开发

Build modern, cross-browser extensions using WXT - the next-generation framework that supports Chrome, Firefox, Edge, Safari, and all Chromium browsers with a single codebase.
使用WXT构建现代化的跨浏览器扩展——这是一款下一代框架,支持通过单一代码库适配Chrome、Firefox、Edge、Safari及所有Chromium内核浏览器。

When to Use This Skill

适用场景

Use this skill when:
  • Creating a new Chrome/browser extension
  • Setting up WXT development environment
  • Building extension features (popup, content scripts, background scripts)
  • Implementing cross-browser compatibility
  • Working with Manifest V3 (mandatory standard as of 2025, V2 deprecated)
  • Integrating React 19, Vue, Svelte, or Solid with extensions
在以下场景中使用本技能:
  • 创建新的Chrome/浏览器扩展
  • 搭建WXT开发环境
  • 开发扩展功能(弹窗、内容脚本、后台脚本)
  • 实现跨浏览器兼容性
  • 基于Manifest V3进行开发(2025年起为强制标准,V2已废弃)
  • 将React 19、Vue、Svelte或Solid集成到扩展中

Quick Start Workflow

快速开始流程

1. Initialize WXT Project

1. 初始化WXT项目

bash
undefined
bash
undefined

Create new project with framework of choice

创建新项目并选择框架

npm create wxt@latest
npm create wxt@latest

Or with specific template

或使用指定模板

npm create wxt@latest -- --template react-ts npm create wxt@latest -- --template vue-ts npm create wxt@latest -- --template svelte-ts
undefined
npm create wxt@latest -- --template react-ts npm create wxt@latest -- --template vue-ts npm create wxt@latest -- --template svelte-ts
undefined

2. Project Structure

2. 项目结构

WXT uses file-based conventions:
project/
├── entrypoints/              # Auto-discovered entry points
│   ├── background.ts         # Service worker
│   ├── content.ts           # Content script
│   ├── popup.html           # Popup UI
│   └── options.html         # Options page
├── components/              # Auto-imported UI components
├── utils/                   # Auto-imported utilities
├── public/                  # Static assets
│   └── icon/               # Extension icons
├── wxt.config.ts           # Configuration
└── package.json
WXT采用基于文件的约定式结构:
project/
├── entrypoints/              # 自动识别的入口文件
│   ├── background.ts         # 服务工作线程
│   ├── content.ts           # 内容脚本
│   ├── popup.html           # 弹窗UI
│   └── options.html         # 选项页面
├── components/              # 自动导入的UI组件
├── utils/                   # 自动导入的工具函数
├── public/                  # 静态资源
│   └── icon/               # 扩展图标
├── wxt.config.ts           # 配置文件
└── package.json

3. Development Commands

3. 开发命令

bash
npm run dev              # Start dev server with HMR
npm run build           # Production build
npm run zip             # Package for store submission
bash
npm run dev              # 启动带热更新的开发服务器
npm run build           # 生产环境构建
npm run zip             # 打包用于应用商店提交

Core Entry Points

核心入口点

WXT recognizes entry points by filename in
entrypoints/
directory:
WXT通过
entrypoints/
目录下的文件名识别入口点:

Background Script (Service Worker)

后台脚本(服务工作线程)

typescript
// entrypoints/background.ts
export default defineBackground({
  type: 'module',
  persistent: false,

  main() {
    // Listen for extension events
    browser.action.onClicked.addListener((tab) => {
      console.log('Extension clicked', tab);
    });

    // Handle messages
    browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
      // Handle message
      sendResponse({ success: true });
      return true; // Keep channel open for async
    });
  },
});
typescript
// entrypoints/background.ts
export default defineBackground({
  type: 'module',
  persistent: false,

  main() {
    // 监听扩展事件
    browser.action.onClicked.addListener((tab) => {
      console.log('Extension clicked', tab);
    });

    // 处理消息
    browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
      // 处理消息
      sendResponse({ success: true });
      return true; // 保持通道开启以支持异步操作
    });
  },
});

Content Script

内容脚本

typescript
// entrypoints/content.ts
export default defineContentScript({
  matches: ['*://*.example.com/*'],
  runAt: 'document_end',

  main(ctx) {
    // Content script logic
    console.log('Content script loaded');

    // Create UI
    const ui = createShadowRootUi(ctx, {
      name: 'my-extension-ui',
      position: 'inline',
      anchor: 'body',

      onMount(container) {
        // Mount React/Vue component
        const root = ReactDOM.createRoot(container);
        root.render(<App />);
      },
    });

    ui.mount();
  },
});
typescript
// entrypoints/content.ts
export default defineContentScript({
  matches: ['*://*.example.com/*'],
  runAt: 'document_end',

  main(ctx) {
    // 内容脚本逻辑
    console.log('Content script loaded');

    // 创建UI
    const ui = createShadowRootUi(ctx, {
      name: 'my-extension-ui',
      position: 'inline',
      anchor: 'body',

      onMount(container) {
        // 挂载React/Vue组件
        const root = ReactDOM.createRoot(container);
        root.render(<App />);
      },
    });

    ui.mount();
  },
});

Popup UI

弹窗UI

typescript
// entrypoints/popup/main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
html
<!-- entrypoints/popup/index.html -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Extension Popup</title>
</head>
<body>
  <div id="root"></div>
  <script type="module" src="./main.tsx"></script>
</body>
</html>
typescript
// entrypoints/popup/main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
html
<!-- entrypoints/popup/index.html -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Extension Popup</title>
</head>
<body>
  <div id="root"></div>
  <script type="module" src="./main.tsx"></script>
</body>
</html>

Configuration

配置

Basic wxt.config.ts

基础wxt.config.ts

typescript
import { defineConfig } from 'wxt';

export default defineConfig({
  // Framework integration
  modules: ['@wxt-dev/module-react'],

  // Manifest configuration
  manifest: {
    name: 'My Extension',
    description: 'Extension description',
    permissions: ['storage', 'activeTab'],
    host_permissions: ['*://example.com/*'],
  },

  // Browser target
  browser: 'chrome', // or 'firefox', 'edge', 'safari'
});
typescript
import { defineConfig } from 'wxt';

export default defineConfig({
  // 框架集成
  modules: ['@wxt-dev/module-react'],

  // 清单配置
  manifest: {
    name: 'My Extension',
    description: 'Extension description',
    permissions: ['storage', 'activeTab'],
    host_permissions: ['*://example.com/*'],
  },

  // 目标浏览器
  browser: 'chrome', // 或 'firefox', 'edge', 'safari'
});

Common Patterns

常见模式

Type-Safe Storage

类型安全存储

typescript
// utils/storage.ts
import { storage } from 'wxt/storage';

export const storageHelper = {
  async get<T>(key: string): Promise<T | null> {
    return await storage.getItem<T>(`local:${key}`);
  },

  async set<T>(key: string, value: T): Promise<void> {
    await storage.setItem(`local:${key}`, value);
  },

  watch<T>(key: string, callback: (newValue: T | null) => void) {
    return storage.watch<T>(`local:${key}`, callback);
  },
};
typescript
// utils/storage.ts
import { storage } from 'wxt/storage';

export const storageHelper = {
  async get<T>(key: string): Promise<T | null> {
    return await storage.getItem<T>(`local:${key}`);
  },

  async set<T>(key: string, value: T): Promise<void> {
    await storage.setItem(`local:${key}`, value);
  },

  watch<T>(key: string, callback: (newValue: T | null) => void) {
    return storage.watch<T>(`local:${key}`, callback);
  },
};

Type-Safe Messaging

类型安全消息传递

typescript
// utils/messaging.ts
interface Messages {
  'get-data': {
    request: { key: string };
    response: { value: any };
  };
}

export async function sendMessage<K extends keyof Messages>(
  type: K,
  payload: Messages[K]['request']
): Promise<Messages[K]['response']> {
  return await browser.runtime.sendMessage({ type, payload });
}
typescript
// utils/messaging.ts
interface Messages {
  'get-data': {
    request: { key: string };
    response: { value: any };
  };
}

export async function sendMessage<K extends keyof Messages>(
  type: K,
  payload: Messages[K]['request']
): Promise<Messages[K]['response']> {
  return await browser.runtime.sendMessage({ type, payload });
}

Script Injection

脚本注入

typescript
// Inject script into page context
import { injectScript } from 'wxt/client';

await injectScript('/injected.js', {
  keepInDom: false,
});
typescript
// 向页面上下文注入脚本
import { injectScript } from 'wxt/client';

await injectScript('/injected.js', {
  keepInDom: false,
});

Building & Deployment

构建与部署

Production Build

生产环境构建

bash
undefined
bash
undefined

Build for specific browser

为特定浏览器构建

npm run build -- --browser=chrome npm run build -- --browser=firefox
npm run build -- --browser=chrome npm run build -- --browser=firefox

Create store-ready ZIP

创建符合应用商店要求的ZIP包

npm run zip npm run zip -- --browser=firefox
undefined
npm run zip npm run zip -- --browser=firefox
undefined

Multi-Browser Build

多浏览器构建

bash
undefined
bash
undefined

Build for all browsers

为所有浏览器构建

npm run zip:all

Output: `.output/my-extension-{version}-{browser}.zip`
npm run zip:all

输出路径:`.output/my-extension-{version}-{browser}.zip`

Modern Stacks (2025)

现代化技术栈(2025年)

Popular technology combinations for building Chrome extensions:
构建Chrome扩展的热门技术组合:

WXT + React + Tailwind + shadcn/ui

WXT + React + Tailwind + shadcn/ui

Most popular stack in 2025. Combines utility-first styling with pre-built accessible components.
bash
npm create wxt@latest -- --template react-ts
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
npx shadcn@latest init
Best for: Modern UIs with consistent design system Example: https://github.com/imtiger/wxt-react-shadcn-tailwindcss-chrome-extension
2025年最受欢迎的技术栈。将实用优先的样式方案与预构建的可访问组件相结合。
bash
npm create wxt@latest -- --template react-ts
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
npx shadcn@latest init
最佳适用场景: 需要现代化UI与一致设计系统的扩展 示例: https://github.com/imtiger/wxt-react-shadcn-tailwindcss-chrome-extension

WXT + React + Mantine UI

WXT + React + Mantine UI

Complete component library with 100+ components and built-in dark mode.
bash
npm create wxt@latest -- --template react-ts
npm install @mantine/core @mantine/hooks
Best for: Feature-rich extensions needing complex components Example: https://github.com/ongkay/WXT-Mantine-Tailwind-Browser-Extension
包含100+组件的完整组件库,内置深色模式支持。
bash
npm create wxt@latest -- --template react-ts
npm install @mantine/core @mantine/hooks
最佳适用场景: 需要复杂组件的功能丰富型扩展 示例: https://github.com/ongkay/WXT-Mantine-Tailwind-Browser-Extension

WXT + React + TypeScript (Minimal)

WXT + React + TypeScript(极简版)

Clean setup for custom designs without UI library dependencies.
bash
npm create wxt@latest -- --template react-ts
Best for: Simple extensions or highly custom designs
无UI库依赖的简洁配置,适用于自定义设计。
bash
npm create wxt@latest -- --template react-ts
最佳适用场景: 简单扩展或高度定制化设计的扩展

Advanced Topics

高级主题

For detailed information on advanced topics, see the reference files:
  • React Integration: See
    references/react-integration.md
    for complete React setup, hooks, state management, and popular UI libraries
  • Chrome APIs: See
    references/chrome-api.md
    for comprehensive Chrome Extension API reference with examples
  • Chrome 140+ Features: See
    references/chrome-140-features.md
    for latest Chrome Extension APIs (sidePanel.getLayout(), etc.)
  • WXT API: See
    references/wxt-api.md
    for complete WXT framework API documentation
  • Best Practices: See
    references/best-practices.md
    for security, performance, and architecture patterns
如需高级主题的详细信息,请参考以下文档:
  • React集成:查看
    references/react-integration.md
    获取完整的React配置、钩子、状态管理及热门UI库使用指南
  • Chrome APIs:查看
    references/chrome-api.md
    获取全面的Chrome扩展API参考及示例
  • Chrome 140+特性:查看
    references/chrome-140-features.md
    了解最新的Chrome扩展API(如sidePanel.getLayout()等)
  • WXT API:查看
    references/wxt-api.md
    获取完整的WXT框架API文档
  • 最佳实践:查看
    references/best-practices.md
    获取安全、性能及架构模式相关建议

Troubleshooting

故障排除

Common issues and solutions:
  1. Module not found errors: Ensure modules are installed and properly imported
  2. CSP violations: Update
    content_security_policy
    in manifest
  3. Hot reload not working: Check browser console for errors
  4. Storage not persisting: Use
    storage.local
    or
    storage.sync
    correctly
For detailed troubleshooting, see
references/troubleshooting.md
常见问题及解决方案:
  1. 模块未找到错误:确保模块已安装并正确导入
  2. CSP违规:更新清单中的
    content_security_policy
    配置
  3. 热更新不生效:检查浏览器控制台中的错误信息
  4. 存储数据不持久:正确使用
    storage.local
    storage.sync
如需详细的故障排除指南,请查看
references/troubleshooting.md

Resources

资源

Official Documentation

官方文档

Bundled Resources

内置资源

  • scripts/: Helper utilities for common extension tasks
  • references/: Detailed documentation for advanced features
  • assets/: Starter templates and example components
Use these resources as needed when building your extension.
  • scripts/:用于常见扩展任务的辅助工具
  • references/:高级功能的详细文档
  • assets/:入门模板及示例组件
构建扩展时可按需使用这些资源。