Skip to content

前端框架

内置模块

WXT 为最流行的前端框架提供了预配置的模块:

安装你所使用框架对应的模块,然后将其添加到配置中:

ts
import { defineConfig } from 'wxt';

export default defineConfig({
  modules: ['@wxt-dev/module-react'],
});
ts
import { defineConfig } from 'wxt';

export default defineConfig({
  modules: ['@wxt-dev/module-vue'],
});
ts
import { defineConfig } from 'wxt';

export default defineConfig({
  modules: ['@wxt-dev/module-svelte'],
});
ts
import { defineConfig } from 'wxt';

export default defineConfig({
  modules: ['@wxt-dev/module-solid'],
});

添加 Vite 插件

如果你的框架没有官方的 WXT 模块,不用担心!WXT 支持任何拥有 Vite 插件的框架。

只需将 Vite 插件添加到配置中即可!在 HTML 页面或 content scripts 中使用该框架,一切都能正常工作。

ts
import { defineConfig } from 'wxt';
import react from '@vitejs/plugin-react';

export default defineConfig({
  vite: () => ({
    plugins: [react()],
  }),
});

WXT 模块只是简化了配置并添加了自动导入功能。它们与上面的方式并没有太大区别。

多个应用实例

由于 Web 扩展通常包含分布在多个入口点(popup、options、changelog、side panel、content scripts 等)中的多个 UI,你需要为每个入口点创建单独的应用实例。

通常,这意味着每个入口点应该是一个目录,其中包含自己的文件。以下是推荐的目录结构:

html
📂 {srcDir}/
   📂 assets/          <---------- 在这里放置共享资源
      📄 tailwind.css
   📂 components/
      📄 Button.tsx
   📂 entrypoints/
      📂 options/       <--------- 使用包含 index.html 文件的文件夹
         📁 pages/      <--------- 如果使用路由,这里适合放置路由页面
         📄 index.html
         📄 App.tsx
         📄 main.tsx    <--------- 在这里创建和挂载你的应用
         📄 style.css   <--------- 入口点专用样式
         📄 router.ts

配置路由

所有框架都提供了基于 URL 路径构建多页面应用的路由器……但 Web 扩展的工作方式与此不同。由于 HTML 文件是静态的,如 chrome-extension://{id}/popup.html,无法更改整个路径来进行路由。

因此,你需要将路由器配置为"hash"模式,在这种模式下,路由信息是 URL 哈希的一部分,而不是路径(例如:popup.html#/popup.html#/account/settings)。

请参阅你所使用的路由器文档,了解 hash 模式及其启用方式。以下是一些常用路由器的参考链接: