mcpField
C
chrome-extension-wxt

chrome-extension-wxt

github.com/tenequm开发40216 次安装5 天前更新
代码仓库

关于 chrome-extension-wxt

使用 WXT 构建浏览器扩展的开发指导技能,面向希望通过统一代码库开发扩展的开发者。内容涵盖入口点、框架设置、跨浏览器构建和常见实现模式。

主要功能

  1. 01初始化 WXT 项目
  2. 02基于文件的扩展入口点
  3. 03React、Vue、Svelte 和 Solid 指导
  4. 04类型安全的存储与消息模式
  5. 05按浏览器进行生产构建
  6. 06打包商店提交用 ZIP

适用场景

  1. 01启动浏览器扩展项目
  2. 02添加弹出窗口和后台脚本
  3. 03构建 Chrome 和 Firefox 版本
  4. 04准备扩展提交包

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/tenequm/skills --skill chrome-extension-wxt

安装后在 Claude Code 中输入/chrome-extension-wxt确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

LICENSE.txt
references/
best-practices.md
chrome-140-features.md
chrome-api.md
react-integration.md
wxt-api.md

详细介绍

使用 WXT 开发 Chrome 扩展

使用 WXT 构建现代跨浏览器扩展。这个新一代框架通过单一代码库支持 Chrome、Firefox、Edge、Safari 和所有 Chromium 浏览器。

何时使用此技能

在以下情况下使用此技能:

  • 创建新的 Chrome/浏览器扩展
  • 设置 WXT 开发环境
  • 构建扩展功能(弹出窗口、内容脚本、后台脚本)
  • 实现跨浏览器兼容性
  • 使用 Manifest V3(截至 2025 年的强制标准,V2 已弃用)
  • 将 React 19、Vue、Svelte 或 Solid 集成到扩展中

快速入门工作流

1. 初始化 WXT 项目
# Create new project with framework of choice
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
2. 项目结构

WXT 使用基于文件的约定:

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
3. 开发命令
npm run dev              # Start dev server with HMR
npm run build           # Production build
npm run zip             # Package for store submission

核心入口点

WXT 根据 entrypoints/ 目录中的文件名识别入口点:

后台脚本(Service Worker)
// 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
    });
  },
});
内容脚本
// 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();
  },
});
弹出窗口 UI
// 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>
);

<!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>

配置

基础 wxt.config.ts
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'
});

常见模式

类型安全的存储
// 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);
  },
};
类型安全的消息传递
// 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 });
}
脚本注入
// Inject script into page context
import { injectScript } from 'wxt/client';

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

构建与部署

生产构建
# Build for specific browser
npm run build -- --browser=chrome
npm run build -- --browser=firefox

# Create store-ready ZIP
npm run zip
npm run zip -- --browser=firefox
多浏览器构建
# Build for all browsers
npm run zip:all

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

现代技术栈(2025 年)

构建 Chrome 扩展的热门技术组合:

WXT + React + Tailwind + shadcn/ui

2025 年最受欢迎的技术栈。结合实用优先的样式设计与预构建的无障碍组件。

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

完整的组件库,包含 100 多个组件并内置深色模式。

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(精简版)

无需依赖 UI 库,为自定义设计提供简洁配置。

npm create wxt@latest -- --template react-ts

最适合: 简单的扩展或高度自定义的设计

高级主题

有关高级主题的详细信息,请参阅参考文件:

  • React 集成:参阅 references/react-integration.md,了解完整的 React 配置、钩子、状态管理和热门 UI 库
  • Chrome API:参阅 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,了解安全性、性能和架构模式

故障排除

常见问题及解决方案:

  1. 找不到模块错误:确保已安装模块并正确导入
  2. CSP 违规:更新清单中的 content_security_policy
  3. 热重载无效:检查浏览器控制台中的错误
  4. 存储未持久化:正确使用 storage.local 或 storage.sync

如需更深入地了解如何避免这些问题,请参阅 references/best-practices.md。

资源

官方文档
随附资源
  • references/:高级功能的详细文档

构建扩展时,可按需使用这些资源。

评论

支持 Markdown