Compare commits

...

77 Commits

Author SHA1 Message Date
GitHub Actions 4f82645c08 chore(release): v0.7.4 2023-10-11 15:59:17 +00:00
Aaron d200c376f8 fix: Support react-refresh when pre-rendering HTML pages in dev mode (#158) 2023-10-11 10:52:48 -05:00
Aaron Klinker b58fb02016 docs: Add migration guides 2023-10-07 10:49:31 -05:00
Aaron e1bab6c746 chore: Upgrade templates to v0.7 (#156) 2023-10-07 10:00:36 -05:00
GitHub Actions d10c22fbd9 chore(release): v0.7.3 2023-10-07 14:59:25 +00:00
Aaron da1f7f3ea5 feat: Support JS entrypoints (#155) 2023-10-07 09:53:47 -05:00
GitHub Actions 2659272f8a chore(release): v0.7.2 2023-10-05 22:17:59 +00:00
Aaron 868fd27804 feat: Allow customizing entrypoint options per browser (#154) 2023-10-05 17:12:20 -05:00
Aaron Klinker d9fdcb5b33 fix: Add missing persistent type to defineBackgroundScript 2023-10-05 16:08:03 -05:00
Aaron Klinker 580793158f fix: Default safari to MV2 2023-10-05 16:07:20 -05:00
Aaron Klinker f58d69dc5f docs: Add docs for development and testing 2023-10-02 15:05:47 -05:00
Aaron c9028dd335 docs: Restructure website to improve UX (#149) 2023-10-02 09:42:46 -05:00
dependabot[bot] 6342f59c5e chore(deps-dev): bump typescript from 5.1 to 5.2 (#148)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Aaron Klinker <aaronklinker1@gmail.com>
2023-10-01 17:58:31 -05:00
dependabot[bot] 2d91898452 chore(deps-dev): bump vitest from 0.34.3 to 0.34.6 (#145)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-01 17:36:48 -05:00
dependabot[bot] 4acefd601c chore(deps-dev): bump vitest-mock-extended from 1.2.1 to 1.3.0 (#147)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-01 17:27:00 -05:00
dependabot[bot] 9a2e71b481 chore(deps-dev): bump @faker-js/faker from 8.0.2 to 8.1.0 (#146)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-01 17:26:20 -05:00
dependabot[bot] 6e578f3156 chore(deps-dev): bump @types/fs-extra from 11.0.1 to 11.0.2 (#144)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-01 17:25:42 -05:00
GitHub Actions 474de83e28 chore(release): v0.7.1 2023-10-01 04:18:14 +00:00
Aaron Klinker 65fcfc0064 docs: Add docs for createContentScriptUi 2023-09-30 23:05:07 -05:00
Aaron Klinker 2d4983e88b chore(release): v0.7.1-alpha1 2023-09-30 21:59:20 -05:00
Aaron 4150e42c05 feat: createContentScriptUi helper (#143) 2023-09-30 21:57:57 -05:00
Aaron 8d7150653a Tweak badge colors for readability 2023-09-30 21:57:16 -05:00
Aaron Klinker 61e57b7b7c Remove all from sync-releases script 2023-09-30 12:49:04 -05:00
Aaron Klinker 83add72312 Update breaking change docs 2023-09-30 12:48:22 -05:00
GitHub Actions 3c723d2c92 chore(release): v0.7.0 2023-09-30 17:45:03 +00:00
Aaron Klinker 1eb35c7207 Reduce codecov requirement to 80% 2023-09-30 12:38:14 -05:00
Aaron 725ecf7c64 fix: Reorder typescript paths to give priority to @ and ~ over @@ and ~~ (#142) 2023-09-30 12:33:33 -05:00
Aaron 3847092df4 feat: Content script cssInjectionMode (#141) 2023-09-30 12:32:00 -05:00
Aaron 19b11c236f fix!: Output content script CSS to content-scripts/<name>.css (#140)
BREAKING CHANGE: Content script CSS used to be output to `assets/<name>.css`, but is now `content-scripts/<name>.css` to match the docs.
2023-09-30 12:20:41 -05:00
Aaron Klinker 4b2012c489 fix: Validate transformed manifest correctly 2023-09-30 10:32:57 -05:00
Aaron Klinker 0591050f31 chore: Store user config metadata in memory
This will be used in #16
2023-09-30 10:30:25 -05:00
GitHub Actions b15dc7fc11 chore(release): v0.6.6 2023-09-30 15:05:16 +00:00
Aaron 89d15babc2 feat: Disable opening browser automatically during dev mode (#136) 2023-09-30 08:45:24 -05:00
GitHub Actions c616125689 chore(release): v0.6.5 2023-09-30 03:15:10 +00:00
Aaron e97071b7d7 fix: Support loading tsx entrypoints (#134) 2023-09-29 22:08:20 -05:00
Aaron 1fa049c5a7 Update badge colors 2023-09-29 12:43:28 -05:00
Aaron Klinker b48cee9715 fix: Don't crash when <all_urls> matches is used in dev mode 2023-09-29 08:18:56 -05:00
Aaron Klinker 24e69fe1bf docs: Add link to update extensions using WXT 2023-09-28 12:26:29 -05:00
Aaron Klinker 41e154992a docs: Fix DX section sizing 2023-09-28 12:22:56 -05:00
Aaron Klinker 55707932a9 docs: Add more content to the homepage 2023-09-28 12:08:21 -05:00
Aaron Klinker 08115a40ae Add explicit title to homepage 2023-09-28 10:22:20 -05:00
Aaron Klinker 96be879918 docs: Add tags for SEO and socials 2023-09-28 10:13:18 -05:00
Aaron 1fc4ada66d Add badges to README 2023-09-27 12:41:37 -05:00
Aaron Klinker d27f299641 Remove files from coverage 2023-09-27 12:27:58 -05:00
Aaron 7183114370 chore: Code coverage improvements (#131) 2023-09-27 12:21:50 -05:00
GitHub Actions 7bd940450f chore(release): v0.6.4 2023-09-27 17:12:03 +00:00
Aaron cf5a7d1411 fix: Use execaCommand instead of node:child_process (#130) 2023-09-27 12:06:44 -05:00
Aaron Klinker 5482b2f934 chore: Increase E2E test timeout
GitHub actions windows fails every once in a while due to a timeout, this should reduce those errors
2023-09-27 11:36:37 -05:00
Aaron Klinker c4a6ff928d Remove Aaron from release contributors 2023-09-27 11:34:18 -05:00
Aaron Klinker 455e7f3765 fix(content-scripts): Don't throw an error when including include or exclude options on a content script 2023-09-27 11:29:50 -05:00
Aaron 25b6ab92f5 chore(templates): Add .wxt directory to gitignore (#129) 2023-09-27 11:24:04 -05:00
GitHub Actions 50f6289ac5 chore(release): v0.6.3 2023-09-26 22:28:00 +00:00
Aaron a0e1b4741e feat(client): Add block and addEventListener utils to ContentScriptContext (#128) 2023-09-26 17:19:56 -05:00
GitHub Actions ab672e9dbd chore(release): v0.6.2 2023-09-25 19:31:40 +00:00
Aaron 7b3ea52e02 feat: Show spinner when building entrypoints (#126) 2023-09-25 14:23:19 -05:00
Aaron e0929a68ba docs: Update vite docs to use function 2023-09-25 00:14:38 -05:00
Aaron 4c430725a5 docs: Fix import typo 2023-09-25 00:10:35 -05:00
Aaron 7d745f6ec7 Remove vercel config
Using netlify
2023-09-23 16:17:10 -05:00
Aaron Klinker 10091d7769 Update feature list 2023-09-23 16:05:43 -05:00
Aaron 2e142b3038 feat: --analyze build flag (#125) 2023-09-23 16:00:35 -05:00
GitHub Actions 361bb2dcc8 chore(release): v0.6.1 2023-09-23 02:13:38 +00:00
Aaron 26fca5c0a2 feat: Add transformManifest option (#124) 2023-09-22 21:08:03 -05:00
Aaron 30a61f4384 fix: Don't open browser during development when using WSL (#123) 2023-09-22 20:32:31 -05:00
Aaron Klinker 8e0a189d77 docs: Load extension details from CWS 2023-09-22 14:37:20 -05:00
Aaron Klinker cae44c9732 Update changelog 2023-09-22 12:47:34 -05:00
GitHub Actions fba8f0d017 chore(release): v0.6.0 2023-09-22 17:45:55 +00:00
Aaron Klinker 3f260ee777 fix: Disable dev logs in production
This closes #119
2023-09-22 12:05:05 -05:00
Aaron Klinker 1f6a931b02 fix: Use the same mode for each build step 2023-09-22 11:57:36 -05:00
Aaron 07891d028b feat!: Require a function for vite configuration (#121)
BREAKING CHANGE: The `vite` config option must now be a function. If you were using an object before, change it from `vite: { ... }` to `vite: () => ({ ... })`.
2023-09-22 11:51:55 -05:00
Aaron Klinker 1f448d1bf0 feat: Export ContentScriptContext from wxt/client 2023-09-22 11:00:28 -05:00
Aaron Klinker 7722986537 Update changelog authors 2023-09-22 10:56:22 -05:00
GitHub Actions 4b73168618 chore(release): v0.5.6 2023-09-22 15:48:35 +00:00
Aaron 16cebc538f feat: Add ContentScriptContext util for stopping invalidated content scripts (#120) 2023-09-21 18:48:07 -05:00
Aaron e4aaba98ab Remove defer from umami script 2023-09-20 21:09:30 -05:00
Aaron c190d8c44c Add umami to docs website 2023-09-20 21:08:51 -05:00
GitHub Actions 5801f96f79 chore(release): v0.5.5 2023-09-19 23:00:53 +00:00
Aaron Klinker 92039b855e fix: Automatically replace vite's process.env.NODE_ENV output in lib mode with the mode 2023-09-19 17:56:10 -05:00
127 changed files with 4322 additions and 979 deletions
+8
View File
@@ -0,0 +1,8 @@
coverage:
status:
project:
default:
informational: true
patch:
default:
informational: true
+5
View File
@@ -51,6 +51,11 @@ jobs:
- name: Tests
run: pnpm test:coverage --reporter=default --reporter=hanging-process
- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v3
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
project-templates:
name: Project Templates
runs-on: ubuntu-22.04
+3 -1
View File
@@ -17,4 +17,6 @@ web-ext.config.ts
templates/*/pnpm-lock.yaml
templates/*/yarn.lock
templates/*/package-lock.json
docs/config.md
docs/api/config.md
docs/api/cli.md
stats.html
+4
View File
@@ -10,3 +10,7 @@ CHANGELOG.md
.prettierignore
*.png
*.svg
*.txt
_gitignore
_redirects
*.svelte
+203 -100
View File
@@ -1,5 +1,207 @@
# Changelog
## v0.7.4
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.7.3...v0.7.4)
### 🩹 Fixes
- Support `react-refresh` when pre-rendering HTML pages in dev mode ([#158](https://github.com/wxt-dev/wxt/pull/158))
### 📖 Documentation
- Add migration guides ([b58fb02](https://github.com/wxt-dev/wxt/commit/b58fb02))
### 🏡 Chore
- Upgrade templates to v0.7 ([#156](https://github.com/wxt-dev/wxt/pull/156))
## v0.7.3
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.7.2...v0.7.3)
### 🚀 Enhancements
- Support JS entrypoints ([#155](https://github.com/wxt-dev/wxt/pull/155))
## v0.7.2
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.7.1...v0.7.2)
### 🚀 Enhancements
- Allow customizing entrypoint options per browser ([#154](https://github.com/wxt-dev/wxt/pull/154))
### 🩹 Fixes
- Default safari to MV2 ([5807931](https://github.com/wxt-dev/wxt/commit/5807931))
- Add missing `persistent` type to `defineBackgroundScript` ([d9fdcb5](https://github.com/wxt-dev/wxt/commit/d9fdcb5))
### 📖 Documentation
- Restructure website to improve UX ([#149](https://github.com/wxt-dev/wxt/pull/149))
- Add docs for development and testing ([f58d69d](https://github.com/wxt-dev/wxt/commit/f58d69d))
### 🏡 Chore
- **deps-dev:** Bump @types/fs-extra from 11.0.1 to 11.0.2 ([#144](https://github.com/wxt-dev/wxt/pull/144))
- **deps-dev:** Bump @faker-js/faker from 8.0.2 to 8.1.0 ([#146](https://github.com/wxt-dev/wxt/pull/146))
- **deps-dev:** Bump vitest-mock-extended from 1.2.1 to 1.3.0 ([#147](https://github.com/wxt-dev/wxt/pull/147))
- **deps-dev:** Bump vitest from 0.34.3 to 0.34.6 ([#145](https://github.com/wxt-dev/wxt/pull/145))
- **deps-dev:** Bump typescript from 5.1 to 5.2 ([#148](https://github.com/wxt-dev/wxt/pull/148))
## v0.7.1
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.7.0...v0.7.1)
### 🚀 Enhancements
- `createContentScriptUi` helper ([#143](https://github.com/wxt-dev/wxt/pull/143))
### 📖 Documentation
- Add docs for `createContentScriptUi` ([65fcfc0](https://github.com/wxt-dev/wxt/commit/65fcfc0))
### 🏡 Chore
- **release:** V0.7.1-alpha1 ([2d4983e](https://github.com/wxt-dev/wxt/commit/2d4983e))
## v0.7.0
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.6.6...v0.7.0)
### 🚀 Enhancements
- Content script `cssInjectionMode` ([#141](https://github.com/wxt-dev/wxt/pull/141))
### 🩹 Fixes
- Validate transformed manifest correctly ([4b2012c](https://github.com/wxt-dev/wxt/commit/4b2012c))
- ⚠️ Output content script CSS to `content-scripts/<name>.css` ([#140](https://github.com/wxt-dev/wxt/pull/140))
- Reorder typescript paths to give priority to `@` and `~` over `@@` and `~~` ([#142](https://github.com/wxt-dev/wxt/pull/142))
### 🏡 Chore
- Store user config metadata in memory ([0591050](https://github.com/wxt-dev/wxt/commit/0591050))
#### ⚠️ Breaking Changes
- ⚠️ Content script CSS used to be output to `assets/<name>.css`, but is now `content-scripts/<name>.css` to match the docs. ([#140](https://github.com/wxt-dev/wxt/pull/140))
## v0.6.6
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.6.5...v0.6.6)
### 🚀 Enhancements
- Disable opening browser automatically during dev mode ([#136](https://github.com/wxt-dev/wxt/pull/136))
## v0.6.5
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.6.4...v0.6.5)
### 🩹 Fixes
- Don't crash when `<all_urls>` matches is used in dev mode ([b48cee9](https://github.com/wxt-dev/wxt/commit/b48cee9))
- Support loading `tsx` entrypoints ([#134](https://github.com/wxt-dev/wxt/pull/134))
### 📖 Documentation
- Add tags for SEO and socials ([96be879](https://github.com/wxt-dev/wxt/commit/96be879))
- Add more content to the homepage ([5570793](https://github.com/wxt-dev/wxt/commit/5570793))
- Fix DX section sizing ([41e1549](https://github.com/wxt-dev/wxt/commit/41e1549))
- Add link to update extensions using WXT ([24e69fe](https://github.com/wxt-dev/wxt/commit/24e69fe))
### 🏡 Chore
- Code coverage improvements ([#131](https://github.com/wxt-dev/wxt/pull/131))
## v0.6.4
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.6.3...v0.6.4)
### 🩹 Fixes
- **content-scripts:** Don't throw an error when including `include` or `exclude` options on a content script ([455e7f3](https://github.com/wxt-dev/wxt/commit/455e7f3))
- Use `execaCommand` instead of `node:child_process` ([#130](https://github.com/wxt-dev/wxt/pull/130))
### 🏡 Chore
- **templates:** Add `.wxt` directory to gitignore ([#129](https://github.com/wxt-dev/wxt/pull/129))
- Increase E2E test timeout ([5482b2f](https://github.com/wxt-dev/wxt/commit/5482b2f))
## v0.6.3
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.6.2...v0.6.3)
### 🚀 Enhancements
- **client:** Add `block` and `addEventListener` utils to `ContentScriptContext` ([#128](https://github.com/wxt-dev/wxt/pull/128))
## v0.6.2
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.6.1...v0.6.2)
### 🚀 Enhancements
- `--analyze` build flag ([#125](https://github.com/wxt-dev/wxt/pull/125))
- Show spinner when building entrypoints ([#126](https://github.com/wxt-dev/wxt/pull/126))
### 📖 Documentation
- Fix import typo ([4c43072](https://github.com/wxt-dev/wxt/commit/4c43072))
- Update vite docs to use function ([e0929a6](https://github.com/wxt-dev/wxt/commit/e0929a6))
## v0.6.1
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.6.0...v0.6.1)
### 🚀 Enhancements
- Add `transformManifest` option ([#124](https://github.com/wxt-dev/wxt/pull/124))
### 🩹 Fixes
- Don't open browser during development when using WSL ([#123](https://github.com/wxt-dev/wxt/pull/123))
### 📖 Documentation
- Load extension details from CWS ([8e0a189](https://github.com/wxt-dev/wxt/commit/8e0a189))
## v0.6.0
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.5.6...v0.6.0)
### 🚀 Enhancements
- Export `ContentScriptContext` from `wxt/client` ([1f448d1](https://github.com/wxt-dev/wxt/commit/1f448d1))
- ⚠️ Require a function for `vite` configuration ([#121](https://github.com/wxt-dev/wxt/pull/121))
### 🩹 Fixes
- Use the same mode for each build step ([1f6a931](https://github.com/wxt-dev/wxt/commit/1f6a931))
- Disable dev logs in production ([3f260ee](https://github.com/wxt-dev/wxt/commit/3f260ee))
#### ⚠️ Breaking Changes
- ⚠️ The `vite` config option must now be a function. If you were using an object before, change it from `vite: { ... }` to `vite: () => ({ ... })`. ([#121](https://github.com/wxt-dev/wxt/pull/121))
## v0.5.6
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.5.5...v0.5.6)
### 🚀 Enhancements
- Add `ContentScriptContext` util for stopping invalidated content scripts ([#120](https://github.com/wxt-dev/wxt/pull/120))
## v0.5.5
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.5.4...v0.5.5)
### 🩹 Fixes
- Automatically replace vite's `process.env.NODE_ENV` output in lib mode with the mode ([92039b8](https://github.com/wxt-dev/wxt/commit/92039b8))
## v0.5.4
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.5.3...v0.5.4)
@@ -9,10 +211,6 @@
- Recognize `background/index.ts` as an entrypoint ([419fab8](https://github.com/wxt-dev/wxt/commit/419fab8))
- Don't warn about deep entrypoint subdirectories not being recognized ([87e8df9](https://github.com/wxt-dev/wxt/commit/87e8df9))
### ❤️ Contributors
- Aaron Klinker <aaronklinker1@gmail.com>
## v0.5.3
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.5.2...v0.5.3)
@@ -25,11 +223,6 @@
- Refactor how config is resolved ([#118](https://github.com/wxt-dev/wxt/pull/118))
### ❤️ Contributors
- Aaron <aaronklinker1@gmail.com>
- Aaron Klinker <aaronklinker1@gmail.com>
## v0.5.2
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.5.1...v0.5.2)
@@ -38,10 +231,6 @@
- Import client utils when getting entrypoint config ([#117](https://github.com/wxt-dev/wxt/pull/117))
### ❤️ Contributors
- Aaron <aaronklinker1@gmail.com>
## v0.5.1
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.5.0...v0.5.1)
@@ -55,11 +244,6 @@
- Allow any string for target browser ([b4de93d](https://github.com/wxt-dev/wxt/commit/b4de93d))
### ❤️ Contributors
- Aaron <aaronklinker1@gmail.com>
- Aaron Klinker <aaronklinker1@gmail.com>
## v0.5.0
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.4.1...v0.5.0)
@@ -89,10 +273,6 @@
- ⚠️ Change default `publicDir` to `<srcDir>/public` ([5f15f9c](https://github.com/wxt-dev/wxt/commit/5f15f9c))
### ❤️ Contributors
- Aaron Klinker ([@aklinker1](https://github.com/aklinker1))
## v0.4.1
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.4.0...v0.4.1)
@@ -105,10 +285,6 @@
- **init:** Don't show `cd .` when initializing the current directory ([e086374](https://github.com/wxt-dev/wxt/commit/e086374))
### ❤️ Contributors
- Aaron Klinker ([@aklinker1](https://github.com/aklinker1))
## v0.4.0
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.3.2...v0.4.0)
@@ -158,10 +334,6 @@
- ⚠️ Use relative path aliases inside `.wxt/tsconfig.json` ([#102](https://github.com/wxt-dev/wxt/pull/102))
### ❤️ Contributors
- Aaron Klinker ([@aklinker1](https://github.com/aklinker1))
## v0.3.2
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.3.1...v0.3.2)
@@ -191,10 +363,6 @@
- List vite version when validating project templates ([ef140dc](https://github.com/wxt-dev/wxt/commit/ef140dc))
- Validate templates using tarball to avoid version conflicts within the `wxt/node_modules` directory ([edfa075](https://github.com/wxt-dev/wxt/commit/edfa075))
### ❤️ Contributors
- Aaron Klinker ([@aklinker1](https://github.com/aklinker1))
## v0.3.1
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.3.0...v0.3.1)
@@ -226,9 +394,8 @@
- Speed up demo validation ([3a9fd39](https://github.com/wxt-dev/wxt/commit/3a9fd39))
- Fix flakey failure when validating templates ([25677ba](https://github.com/wxt-dev/wxt/commit/25677ba))
### ❤️ Contributors
### ❤️ Contributors
- Aaron Klinker ([@aklinker1](https://github.com/aklinker1))
- BeanWei ([@BeanWei](https://github.com/BeanWei))
## v0.3.0
@@ -262,10 +429,6 @@
- ⚠️ Add type safety to `browser.runtime.getURL` ([58a84ec](https://github.com/wxt-dev/wxt/commit/58a84ec))
- ⚠️ Change default `publicDir` to `<rootDir>/public` ([19c0948](https://github.com/wxt-dev/wxt/commit/19c0948))
### ❤️ Contributors
- Aaron Klinker ([@aklinker1](https://github.com/aklinker1))
## v0.2.5
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.2.4...v0.2.5)
@@ -288,10 +451,6 @@
- Validate project templates ([9ac756f](https://github.com/wxt-dev/wxt/commit/9ac756f))
### ❤️ Contributors
- Aaron Klinker ([@aklinker1](https://github.com/aklinker1))
## v0.2.4
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.2.3...v0.2.4)
@@ -300,10 +459,6 @@
- Add `wxt zip` command ([#47](https://github.com/wxt-dev/wxt/pull/47))
### ❤️ Contributors
- Aaron Klinker ([@aklinker1](https://github.com/aklinker1))
## v0.2.3
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.2.2...v0.2.3)
@@ -314,10 +469,6 @@
- Read boolean maniest options from meta tags correctly ([495c5c8](https://github.com/wxt-dev/wxt/commit/495c5c8))
- Some fields cannot be overridden from `config.manifest` ([#46](https://github.com/wxt-dev/wxt/pull/46))
### ❤️ Contributors
- Aaron Klinker ([@aklinker1](https://github.com/aklinker1))
## v0.2.2
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.2.1...v0.2.2)
@@ -326,10 +477,6 @@
- Register content scripts correctly in dev mode ([2fb5a54](https://github.com/wxt-dev/wxt/commit/2fb5a54))
### ❤️ Contributors
- Aaron Klinker ([@aklinker1](https://github.com/aklinker1))
## v0.2.1
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.2.0...v0.2.1)
@@ -342,10 +489,6 @@
- Remove HMR log ([90fa6bf](https://github.com/wxt-dev/wxt/commit/90fa6bf))
### ❤️ Contributors
- Aaron Klinker ([@aklinker1](https://github.com/aklinker1))
## v0.2.0
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.1.6...v0.2.0)
@@ -370,10 +513,6 @@
- ⚠️ Rename `defineBackgroundScript` to `defineBackground` ([5b48ae9](https://github.com/wxt-dev/wxt/commit/5b48ae9))
### ❤️ Contributors
- Aaron Klinker ([@aklinker1](https://github.com/aklinker1))
## v0.1.6
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.1.5...v0.1.6)
@@ -388,10 +527,6 @@
- React and Vue starter templates ([#33](https://github.com/wxt-dev/wxt/pull/33))
- Svelte template ([#34](https://github.com/wxt-dev/wxt/pull/34))
### ❤️ Contributors
- Aaron Klinker ([@aklinker1](https://github.com/aklinker1))
## v0.1.5
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.1.4...v0.1.5)
@@ -400,10 +535,6 @@
- Include `vite/client` types ([371be99](https://github.com/wxt-dev/wxt/commit/371be99))
### ❤️ Contributors
- Aaron Klinker ([@aklinker1](https://github.com/aklinker1))
## v0.1.4
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.1.3...v0.1.4)
@@ -421,10 +552,6 @@
- Update prettier ignore ([68611ae](https://github.com/wxt-dev/wxt/commit/68611ae))
### ❤️ Contributors
- Aaron Klinker ([@aklinker1](https://github.com/aklinker1))
## v0.1.3
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.1.2...v0.1.3)
@@ -446,10 +573,6 @@
- Upgrade to pnpm 8 ([0ce7c9d](https://github.com/wxt-dev/wxt/commit/0ce7c9d))
### ❤️ Contributors
- Aaron Klinker ([@aklinker1](https://github.com/aklinker1))
## v0.1.2
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.1.1...v0.1.2)
@@ -468,10 +591,6 @@
- Change `config.vite` to `UserConfig` ([ef6001e](https://github.com/wxt-dev/wxt/commit/ef6001e))
### ❤️ Contributors
- Aaron Klinker ([@aklinker1](https://github.com/aklinker1))
## v0.1.1
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.1.0...v0.1.1)
@@ -481,10 +600,6 @@
- Allow dashes in entrypoint names ([2e51e73](https://github.com/wxt-dev/wxt/commit/2e51e73))
- Unable to read entrypoint options ([#28](https://github.com/wxt-dev/wxt/pull/28))
### ❤️ Contributors
- Aaron Klinker ([@aklinker1](https://github.com/aklinker1))
## v0.1.0
Initial release of WXT. Full support for production builds and initial toolkit for development:
@@ -508,10 +623,6 @@ Initial release of WXT. Full support for production builds and initial toolkit f
- Create github release ([b7c078f](https://github.com/wxt-dev/wxt/commit/b7c078f))
### ❤️ Contributors
- Aaron Klinker ([@aklinker1](https://github.com/aklinker1))
## v0.0.2
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.0.1...v0.0.2)
@@ -542,10 +653,6 @@ Initial release of WXT. Full support for production builds and initial toolkit f
- Rename `templates` to `virtual-modules` ([#24](https://github.com/wxt-dev/wxt/pull/24))
- Update cli screenshot ([54eb118](https://github.com/wxt-dev/wxt/commit/54eb118))
### ❤️ Contributors
- Aaron Klinker ([@aklinker1](https://github.com/aklinker1))
## v0.0.1
[compare changes](https://github.com/wxt-dev/wxt/compare/v0.0.0...v0.0.1)
@@ -615,7 +722,3 @@ Initial release of WXT. Full support for production builds and initial toolkit f
- Create validation workflow ([#12](https://github.com/wxt-dev/wxt/pull/12))
- Create release workflow ([#13](https://github.com/wxt-dev/wxt/pull/13))
### ❤️ Contributors
- Aaron Klinker ([@aklinker1](https://github.com/aklinker1))
+19 -5
View File
@@ -3,6 +3,20 @@
<span>WXT</span>
</h1>
<p align="center">
<a href="https://www.npmjs.com/package/wxt" target="_blank">
<img alt="npm" src="https://img.shields.io/npm/v/wxt?labelColor=black&color=%234fa048">
</a>
<span> </span>
<img alt="npm" src="https://img.shields.io/npm/dm/wxt?labelColor=black&color=%234fa048">
<span> </span>
<img alt="NPM" src="https://img.shields.io/npm/l/wxt?labelColor=black&color=%234fa048">
<span> </span>
<a href="https://codecov.io/github/wxt-dev/wxt" target="_blank">
<img alt="Codecov" src="https://img.shields.io/codecov/c/github/wxt-dev/wxt?labelColor=black&color=%234fa048">
</a>
</p>
<p align="center">
<span>Next-gen framework for developing web extensions.</span>
<br/>
@@ -14,11 +28,11 @@
<p align="center">
<a href="https://wxt.dev" target="_blank">Get Started</a>
&bull;
<a href="https://wxt.dev/get-started/installation.html" target="_blank">Installation</a>
<a href="https://wxt.dev/guide/installation.html" target="_blank">Installation</a>
&bull;
<a href="https://wxt.dev/guide/background.html" target="_blank">Entrypoints</a>
<a href="https://wxt.dev/entrypoints/background.html" target="_blank">Entrypoints</a>
&bull;
<a href="https://wxt.dev/config.html" target="_blank">Configuration</a>
<a href="https://wxt.dev/api/config.html" target="_blank">Configuration</a>
</p>
![Example CLI Output](./docs/assets/cli-output.png)
@@ -31,7 +45,7 @@ Bootstrap a new project:
pnpx wxt@latest init <project-name>
```
Or see the [installation guide](https://wxt.dev/get-started/installation.html) to get started with WXT.
Or see the [installation guide](https://wxt.dev/guide/installation.html) to get started with WXT.
## Features
@@ -44,10 +58,10 @@ Or see the [installation guide](https://wxt.dev/get-started/installation.html) t
- ⬇️ Download and bundle remote URL imports
- 🎨 Frontend framework agnostic: works with Vue, React, Svelte, etc
- 🖍️ Quickly bootstrap a new project
- 📏 Bundle analysis
### Coming Soon
- 📏 Bundle analysis
- 🤖 Automated publishing
## Contributors
+5 -1
View File
@@ -16,9 +16,13 @@
"postinstall": "pnpm -w build && wxt prepare"
},
"dependencies": {
"webextension-polyfill": "^0.10.0"
"webextension-polyfill": "^0.10.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/react": "^18.2.14",
"@types/react-dom": "^18.2.6",
"@types/webextension-polyfill": "^0.10.0",
"sass": "^1.64.0",
"wxt": "workspace:*"
+2
View File
@@ -19,4 +19,6 @@ export default defineBackground(() => {
browser.i18n.getMessage('hello', 'Aaron');
browser.i18n.getMessage('bye', ['Aaron']);
browser.i18n.getMessage('@@extension_id');
console.log('WXT MODE:', import.meta.env.MODE);
});
@@ -0,0 +1,25 @@
import ReactDOM from 'react-dom/client';
export default defineContentScript({
matches: ['<all_urls>'],
async main(ctx) {
console.log(browser.runtime.id);
logId();
console.log('WXT MODE:', import.meta.env.MODE);
const n = (Math.random() * 100).toFixed(1);
ctx.setInterval(() => {
console.log(n, browser.runtime.id);
}, 1e3);
const container = document.createElement('div');
document.body.append(container);
ReactDOM.createRoot(container).render(<SomeComponent />);
},
});
function SomeComponent() {
return <div>Some component</div>;
}
+2
View File
@@ -3,3 +3,5 @@ import 'url:https://code.jquery.com/jquery-3.7.1.slim.min.js';
console.log(browser.runtime.id);
logId();
console.log(2);
console.log('WXT MODE:', import.meta.env.MODE);
@@ -1,10 +0,0 @@
import '../../common/style.css';
export default defineContentScript({
matches: ['*://*/*'],
async main() {
console.log(browser.runtime.id);
logId();
mountContentScriptUi();
},
});
+24
View File
@@ -0,0 +1,24 @@
import '../../common/style.css';
import './style.css';
export default defineContentScript({
matches: ['https://*.duckduckgo.com/*'],
cssInjectionMode: 'ui',
async main(ctx) {
const ui = await createContentScriptUi(ctx, {
name: 'demo-ui',
type: 'inline',
append: 'before',
anchor: 'form[role=search]',
mount: (container) => {
const app = document.createElement('div');
app.textContent = 'Custom content script UI';
container.append(app);
},
});
ui.mount();
setTimeout(ui.remove, 5000);
},
});
+11
View File
@@ -0,0 +1,11 @@
:root {
color-scheme: dark;
color: indianred;
}
html {
background-color: black;
}
div {
padding: 16px;
}
+5 -1
View File
@@ -1,3 +1,7 @@
{
"extends": ["../tsconfig.base.json", "./.wxt/tsconfig.json"]
"extends": ["../tsconfig.base.json", "./.wxt/tsconfig.json"],
"compilerOptions": {
"allowImportingTsExtensions": true,
"jsx": "react-jsx"
}
}
+110 -43
View File
@@ -1,26 +1,68 @@
<script lang="ts" setup>
const extensions = [
{
name: 'GitHub: Better Line Counts',
description: 'Remove generated files from GitHub line counts.',
icon: 'https://lh3.googleusercontent.com/GcffNyCJaxT2G9dsQCJHhUEMlu_E0vEzph5cLPrQj7UHKat7QyCzGu69Dmp_DDUL8rY-bPMFJceQarS1wcqdwTalTg=s256',
link: 'https://chrome.google.com/webstore/detail/github-better-line-counts/ocfdgncpifmegplaglcnglhioflaimkd',
},
import { computed } from 'vue';
import useListExtensionDetails, {
ChromeExtension,
} from '../composables/useListExtensionDetails';
// Add extension IDs here. Order doesn't matter, will be sorted by weekly active users
const chromeExtensionIds = [
'ocfdgncpifmegplaglcnglhioflaimkd', // GitHub: Better Line Counts
'mgmdkjcljneegjfajchedjpdhbadklcf', // Anime Skip Player
];
const { data } = useListExtensionDetails(chromeExtensionIds);
const sortedExtensions = computed(() =>
!data.value
? undefined
: [...data.value].sort((l, r) => r.weeklyActiveUsers - l.weeklyActiveUsers),
);
function getStoreUrl(extension: ChromeExtension) {
const url = new URL(extension.storeUrl);
url.searchParams.set('utm_source', 'wxt.dev');
return url.href;
}
</script>
<template>
<section class="vp-doc">
<div class="container">
<h2>Who's Using WXT?</h2>
<p>
Battle tested and ready for production. Explore chrome extensions made
with WXT.
</p>
<ul>
<li v-for="extension of extensions">
<img :src="extension.icon" :alt="`${extension.name} icon`" />
<a :href="extension.link" target="_blank">{{ extension.name }}</a>
<small>{{ extension.description }}</small>
<li v-for="extension of sortedExtensions">
<img
:src="extension.iconUrl"
:alt="`${extension.name} icon`"
referrerpolicy="no-referrer"
/>
<div>
<a
:href="getStoreUrl(extension)"
target="_blank"
:title="extension.name"
>{{ extension.name }}</a
>
<p class="description" :title="extension.shortDescription">
{{ extension.shortDescription }}
</p>
<p class="user-count">
{{ extension.weeklyActiveUsers.toLocaleString() }} users
</p>
</div>
</li>
</ul>
<p>Open a PR to add your extension to the list!</p>
<p class="centered pr">
<a
href="https://github.com/wxt-dev/wxt/edit/main/docs/.vitepress/components/UsingWxtSection.vue"
target="_blank"
>Open a PR</a
>
to add your extension to the list!
</p>
</div>
</section>
</template>
@@ -30,10 +72,6 @@ const extensions = [
padding: 0 24px;
}
h2 {
margin-bottom: 32px;
}
@media (min-width: 640px) {
.vp-doc {
padding: 0 48px;
@@ -53,57 +91,86 @@ h2 {
flex-direction: column;
}
img {
width: 96px;
height: 96px;
margin-bottom: 16px;
li img {
width: 116px;
height: 116px;
padding: 16px;
border-radius: 8px;
background-color: var(--vp-c-default-soft);
}
ul {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-template-columns: repeat(1, 1fr);
align-items: stretch;
gap: 16px;
list-style: none;
margin: 0;
margin: 16px 0;
padding: 0;
}
@media (min-width: 640px) {
ul {
grid-template-columns: repeat(3, 1fr);
}
}
@media (min-width: 960px) {
ul {
grid-template-columns: repeat(4, 1fr);
grid-template-columns: repeat(2, 1fr);
}
}
li {
margin: 0 !important;
padding: 12px;
padding: 16px;
display: flex;
flex-direction: column;
align-items: center;
background-color: var(--vp-c-bg-soft);
border-radius: 12px;
flex: 1;
}
a,
small {
text-align: center;
}
small {
opacity: 50%;
gap: 16px;
}
p {
.centered {
text-align: center;
opacity: 50%;
}
a {
color: var(--vp-c-text-1);
li a,
li .user-count,
li .description {
padding: 0;
margin: 0;
}
li .user-count {
opacity: 70%;
text-align: right;
width: 100%;
font-size: small;
}
li a {
display: -webkit-box;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
overflow: hidden;
cursor: pointer;
padding: 0;
margin: 0;
text-decoration: none;
}
li a:hover {
text-decoration: underline;
}
li div {
flex: 1;
display: flex;
flex-direction: column;
}
li .description {
opacity: 90%;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
flex-grow: 1;
}
.pr {
opacity: 70%;
}
</style>
@@ -0,0 +1,53 @@
import { ref } from 'vue';
export interface ChromeExtension {
id: string;
name: string;
iconUrl: string;
weeklyActiveUsers: number;
shortDescription: string;
storeUrl: string;
}
const operationName = 'WxtDocsUsedBy';
const query = `query ${operationName}($ids:[String!]!) {
chromeExtensions(ids: $ids) {
id
name
iconUrl
weeklyActiveUsers
shortDescription
storeUrl
}
}`;
export default function (ids: string[]) {
const data = ref<ChromeExtension[]>();
const err = ref<unknown>();
fetch('https://queue.wxt.dev/api', {
method: 'POST',
body: JSON.stringify({
operationName,
query,
variables: { ids },
}),
})
.then(async (res) => {
const {
data: { chromeExtensions },
} = await res.json();
data.value = chromeExtensions;
err.value = undefined;
})
.catch((error) => {
console.error(error);
data.value = undefined;
err.value = error;
});
return {
data,
err,
};
}
+88 -36
View File
@@ -1,19 +1,53 @@
import { defineConfig } from 'vitepress';
import { generateConfigDocs } from './plugins/generate-config-docs';
import { generateCliDocs } from './plugins/generate-cli-docs';
const title = 'Next-gen Web Extension Framework';
const titleSuffix = ' WXT';
const description =
"WXT provides the best developer experience, making it quick, easy, and fun to develop chrome extensions for all browsers. With built-in utilties for building, zipping, and publishing your extension, it's easy to get started.";
const ogTitle = `${title}${titleSuffix}`;
const ogUrl = 'https://wxt.dev';
const ogImage = 'https://wxt.dev/social-preview.png';
// https://vitepress.dev/reference/site-config
export default defineConfig({
titleTemplate: `:title${titleSuffix}`,
title: 'WXT',
description,
vite: {
clearScreen: false,
plugins: [generateConfigDocs()],
plugins: [generateConfigDocs(), generateCliDocs()],
},
description: 'Next gen framework for developing web extensions',
lastUpdated: true,
sitemap: {
hostname: 'https://wxt.dev',
},
head: [
['meta', { property: 'og:type', content: 'website' }],
['meta', { property: 'og:title', content: ogTitle }],
['meta', { property: 'og:image', content: ogImage }],
['meta', { property: 'og:url', content: ogUrl }],
['meta', { property: 'og:description', content: description }],
['meta', { name: 'twitter:card', content: 'summary_large_image' }],
[
'script',
{
async: '',
'data-website-id': 'c1840c18-a12c-4a45-a848-55ae85ef7915',
src: 'https://umami.aklinker1.io/script.js',
},
],
],
themeConfig: {
// https://vitepress.dev/reference/default-theme-config
logo: '/logo.svg',
logo: {
src: '/logo.svg',
alt: 'WXT logo',
},
editLink: {
pattern: 'https://github.com/wxt-dev/wxt/edit/main/docs/:path',
},
@@ -22,56 +56,74 @@ export default defineConfig({
},
nav: [
{ text: 'Get Started', link: '/get-started/installation.md' },
{ text: 'Guide', link: '/guide/auto-imports.md' },
{ text: 'Config', link: '/config.md' },
{ text: 'API', link: '/api.md' },
{ text: 'Guide', link: '/guide/installation.md' },
{ text: 'Entrypoints', link: '/entrypoints/background.md' },
{ text: 'API', link: '/api/cli.md' },
],
sidebar: {
'/get-started/': [
{
text: 'Get Started',
items: [
{ text: 'Introduction', link: '/get-started/introduction.md' },
{ text: 'Installation', link: '/get-started/installation.md' },
{ text: 'Configuration', link: '/get-started/configuration.md' },
{ text: 'Entrypoints', link: '/get-started/entrypoints.md' },
{ text: 'Assets', link: '/get-started/assets.md' },
{ text: 'Build Targets', link: '/get-started/build-targets.md' },
{ text: 'Publishing', link: '/get-started/publishing.md' },
{ text: 'Testing', link: '/get-started/testing.md' },
{ text: 'Compare', link: '/get-started/compare.md' },
],
},
],
'/guide/': [
{
text: 'Guide',
items: [
{ text: 'Introduction', link: '/guide/introduction.md' },
{ text: 'Installation', link: '/guide/installation.md' },
{ text: 'Configuration', link: '/guide/configuration.md' },
{ text: 'Entrypoints', link: '/guide/entrypoints.md' },
{ text: 'Assets', link: '/guide/assets.md' },
{ text: 'Multiple Browsers', link: '/guide/multiple-browsers.md' },
{ text: 'Publishing', link: '/guide/publishing.md' },
{ text: 'Auto-imports', link: '/guide/auto-imports.md' },
{ text: 'Manifest.json', link: '/guide/manifest.md' },
{ text: 'Extension APIs', link: '/guide/extension-apis.md' },
{ text: 'Remote Code', link: '/guide/remote-code.md' },
{ text: 'Development', link: '/guide/development.md' },
{ text: 'Testing', link: '/guide/testing.md' },
{ text: 'Vite', link: '/guide/vite.md' },
],
},
{
text: 'Other',
items: [
{ text: 'Migrate to WXT', link: '/guide/migrate-to-wxt.md' },
{ text: 'Compare', link: '/guide/compare.md' },
],
},
],
'/entrypoints/': [
{
text: 'Entrypoints',
items: [
{ text: 'Background', link: '/guide/background.md' },
{ text: 'Bookmarks', link: '/guide/bookmarks.md' },
{ text: 'Content Scripts', link: '/guide/content-scripts.md' },
{ text: 'CSS', link: '/guide/css.md' },
{ text: 'Devtools', link: '/guide/devtools.md' },
{ text: 'History', link: '/guide/history.md' },
{ text: 'Newtab', link: '/guide/newtab.md' },
{ text: 'Options', link: '/guide/options.md' },
{ text: 'Popup', link: '/guide/popup.md' },
{ text: 'Sandbox', link: '/guide/sandbox.md' },
{ text: 'Sidepanel', link: '/guide/sidepanel.md' },
{ text: 'Unlisted Pages', link: '/guide/unlisted-pages.md' },
{ text: 'Unlisted Scripts', link: '/guide/unlisted-scripts.md' },
{ text: 'Background', link: '/entrypoints/background.md' },
{ text: 'Bookmarks', link: '/entrypoints/bookmarks.md' },
{
text: 'Content Scripts',
link: '/entrypoints/content-scripts.md',
},
{ text: 'CSS', link: '/entrypoints/css.md' },
{ text: 'Devtools', link: '/entrypoints/devtools.md' },
{ text: 'History', link: '/entrypoints/history.md' },
{ text: 'Newtab', link: '/entrypoints/newtab.md' },
{ text: 'Options', link: '/entrypoints/options.md' },
{ text: 'Popup', link: '/entrypoints/popup.md' },
{ text: 'Sandbox', link: '/entrypoints/sandbox.md' },
{ text: 'Sidepanel', link: '/entrypoints/sidepanel.md' },
{ text: 'Unlisted Pages', link: '/entrypoints/unlisted-pages.md' },
{
text: 'Unlisted Scripts',
link: '/entrypoints/unlisted-scripts.md',
},
].sort((l, r) => l.text.localeCompare(r.text)),
},
],
'/api/': [
{
items: [
{ text: 'CLI', link: '/api/cli.md' },
{ text: 'Config', link: '/api/config.md' },
{ text: 'wxt', link: '/api/wxt.md' },
{ text: 'wxt/browser', link: '/api/wxt-browser.md' },
{ text: 'wxt/client', link: '/api/wxt-client.md' },
],
},
],
@@ -0,0 +1,108 @@
import { relative, resolve } from 'node:path';
import { readFileSync, writeFileSync } from 'node:fs';
import { format } from 'prettier';
import consola from 'consola';
import { execaCommand } from 'execa';
let hasGenerated = false;
const cliDir = resolve('src/cli/commands');
const cliDirGlob = resolve(cliDir, '**');
const cliTemplatePath = resolve('docs/api/cli.tpl.md');
const cliPath = resolve('docs/api/cli.md');
const PREFACE = `<!--
DO NOT EDIT
Generated by \`wxt/docs/.vitepress/plugins/generate-config-docs.ts\`
To make changes to the config reference, update the JSDoc in \`src/core/types/external.ts\`.
-->`;
export function generateCliDocs() {
writeFileSync(cliPath, '');
const generateDocs = async () => {
consola.info(`Generating ${relative(process.cwd(), cliPath)}`);
try {
const res = await execaCommand('pnpm -s wxt --help');
const dev = splitInfo(res.stdout);
const lines: Array<string | string[]> = [
`## \`wxt\``,
'```sh',
dev.rest,
'```',
];
const commands = await Promise.all(
extractCommands(dev.info).map(async (command) => {
const res = await execaCommand(`pnpm -s wxt ${command} --help`);
const { rest: docs } = splitInfo(res.stdout);
return [`## \`wxt ${command}\``, '```sh', docs, '```'];
}),
);
lines.push(...commands);
const text = await format(
PREFACE +
'\n\n' +
readFileSync(cliTemplatePath, 'utf-8').replace(
'{{ DOCS }}',
lines.flat().join('\n'),
),
{ parser: 'markdown' },
);
writeFileSync(cliPath, text);
consola.success(`Generated ${relative(process.cwd(), cliPath)}`);
} catch (err) {
consola.fail(`Failed to generate ${relative(process.cwd(), cliPath)}`);
consola.error(err.message);
}
};
return {
name: 'docs:generate-cli-docs',
async config() {
if (!hasGenerated) {
hasGenerated = true;
await generateDocs();
}
},
configureServer(server: any) {
server.watcher.add(cliDirGlob);
},
async handleHotUpdate(ctx: { file: string }) {
if (ctx.file === cliTemplatePath || ctx.file.includes(cliDir)) {
await generateDocs();
}
},
};
}
function splitInfo(text: string): { info: string; rest: string } {
const infoStart = text.indexOf('For more info,');
const infoEnd = text.indexOf('\n\nOptions:');
if (infoStart === -1 || infoEnd === -1) {
return { info: '', rest: text };
}
const info = text.substring(infoStart, infoEnd).trim();
const rest = text.replace(info, '').trim().replace('\n\n\n\n', '\n\n');
return { info, rest };
}
function extractCommands(info: string): string[] {
const commands: string[] = [];
// Split the info by line and iterate through each line
info.split('\n').forEach((line) => {
// Use regex to capture the command after "$ wxt " and before "--help"
const match = line.match(/\$ wxt (\w+) --help/);
if (match && match[1]) {
commands.push(match[1]);
}
});
return commands;
}
@@ -1,4 +1,4 @@
import { resolve } from 'node:path';
import { relative, resolve } from 'node:path';
import { Project, ts, Type, Node, JSDocableNode } from 'ts-morph';
import { readFileSync, writeFileSync } from 'node:fs';
import { format } from 'prettier';
@@ -7,8 +7,8 @@ import consola from 'consola';
let hasGenerated = false;
const externalTypesPath = resolve('src/core/types/external.ts');
const configTemplatePath = resolve('docs/config.tpl.md');
const configPath = resolve('docs/config.md');
const configTemplatePath = resolve('docs/api/config.tpl.md');
const configPath = resolve('docs/api/config.md');
const PREFACE = `<!--
DO NOT EDIT
@@ -39,7 +39,7 @@ export function generateConfigDocs() {
writeFileSync(configPath, '');
const generateDocs = async () => {
consola.info('Generating /config.md');
consola.info(`Generating ${relative(process.cwd(), configPath)}`);
try {
const project = new Project({
tsConfigFilePath: resolve('tsconfig.json'),
@@ -118,9 +118,9 @@ export function generateConfigDocs() {
);
writeFileSync(configPath, text);
consola.success('Generated /config.md');
consola.success(`Generated ${relative(process.cwd(), configPath)}`);
} catch (err) {
consola.fail('Failed to generate /config.md');
consola.fail(`Failed to generate ${relative(process.cwd(), configPath)}`);
consola.error(err.message);
}
};
-5
View File
@@ -1,5 +0,0 @@
# API Reference
:::warning 🚧&ensp;Under construction
This documentation does not exist yet.
:::
+5
View File
@@ -0,0 +1,5 @@
# CLI Reference
> Reference generated from `wxt <command> --help`
{{ DOCS }}
+5
View File
@@ -0,0 +1,5 @@
# Config Reference
All the options you can use in your `wxt.config.ts` file.
{{ DOCS }}
+10
View File
@@ -0,0 +1,10 @@
# `wxt/browser` Reference
:::warning 🚧&ensp;Under construction
This documentation does not exist yet. All APIs are documented with JSDoc, so for now, you can view the documentation in your editor.
```ts
import { browser } from 'wxt/browser';
```
:::
+14
View File
@@ -0,0 +1,14 @@
# `wxt/client` Reference
:::warning 🚧&ensp;Under construction
This documentation does not exist yet. All APIs are documented with JSDoc, so for now, you can view the documentation in your editor.
```ts
import {
createContentScriptUi,
defineBackground,
defineContentScript,
} from 'wxt/client';
```
:::
+17
View File
@@ -0,0 +1,17 @@
# `wxt` Reference
:::warning 🚧&ensp;Under construction
This documentation does not exist yet. All APIs are documented with JSDoc, so for now, you can view the documentation in your editor.
```ts
import {
build,
clean,
createServer,
defineConfig,
defineRunnerConfig,
version,
} from 'wxt';
```
:::
-5
View File
@@ -1,5 +0,0 @@
# Config Reference
Discover all the options you can use in your `wxt.config.ts` file.
{{ DOCS }}
@@ -8,8 +8,8 @@ For MV2, the background is added as a script to the background page. For MV3, th
<EntrypointPatterns
:patterns="[
['background.ts', 'background.js'],
['background/index.ts', 'background.js'],
['background.[jt]s', 'background.js'],
['background/index.[jt]s', 'background.js'],
]"
/>
+292
View File
@@ -0,0 +1,292 @@
# Content Scripts
[Chrome Docs](https://developer.chrome.com/docs/extensions/mv3/content_scripts/) &bull; [Firefox Docs](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts)
When creating content script entrypoints, they are automatically included in the `manifest.json` along with any CSS files they import.
## Filenames
<EntrypointPatterns
:patterns="[
['content.[jt]sx?', 'content-scripts/content.js'],
['content/index.[jt]sx?', 'content-scripts/content.js'],
['<name>.content.[jt]sx?', 'content-scripts/<name>.js'],
['<name>.content/index.[jt]sx?', 'content-scripts/<name>.js'],
]"
/>
## Definition
```ts
export default defineContentScript({
// Set manifest options
matches: ['*://google.com/*', '*://duckduckgo.com/*'],
excludeMatches: undefined | [],
includeGlobs: undefined | [],
excludeGlobs: undefined | [],
allFrames: undefined | [],
runAt: undefined | 'document_start' | 'document_end' | 'document_idle',
matchAboutBlank: undefined | true | false,
matchOriginAsFallback: undefined | true | false,
world: undefined | 'ISOLATED' | 'MAIN',
// Set include/exclude if the background should be removed from some builds
include: undefined | string[],
exclude: undefined | string[],
// Configure how CSS is injected onto the page
cssInjectionMode: undefined | "manifest" | "manual" | "ui",
main(ctx) {
// Executed when content script is loaded
},
});
```
> All manifest options default to `undefined`.
When defining multiple content scripts, content script entrypoints that have the same set of options will be merged into a single `content_script` item in the manifest.
## Context
Old content scripts are not automatically stopped when an extension updates and reloads. Often, this leads to "Invalidated context" errors in production when a content script from an old version of your extension tries to use a extension API.
WXT provides a utility for managing this process: `ContentScriptContext`. An instance of this class is provided to you automatically inside the `main` function of your content script.
```ts
export default defineContentScript({
// ...
main(ctx: ContentScriptContext) {
// Add custom listeners for stopping work
ctx.onInvalidated(() => {
// ...
});
// Stop fetch requests
fetch('...url', { signal: ctx.signal });
// Timeout utilities
ctx.setTimeout(() => {
// ...
}, 5e3);
ctx.setInterval(() => {
// ...
}, 60e3);
},
});
```
The class extends [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) and provides other utilities for stopping a content script's logic once it becomes invalidated.
:::tip
When working with content scripts, **you should always use the `ctx` object to stop any async or future work.**
This prevents old content scripts from interfering with new content scripts, and prevents error messages from the console in production.
:::
## CSS
To include CSS with your content script, import the CSS file at the top of your entrypoint.
```
<srcDir>
└─ entrypoints/
└─ overlay.content/
├─ index.ts
└─ style.css
```
```ts
// entrypoints/overlay.content/index.ts
import './style.css';
export default defineContentScript({
matches: ['*://google.com/*', '*://duckduckgo.com/*'],
main(ctx) {
// ...
},
});
```
Any styles imported in your content script will be added to that content script's `css` array in your `manifest.json`:
```json
// .output/chrome-mv3/manifest.json
{
"content_scripts": [
{
"matches": ["*://google.com/*", "*://duckduckgo.com/*"],
"js": ["content-scripts/overlay.js"],
"css": ["content-scripts/overlay.css"]
}
]
}
```
To disable this behavior, set `cssInjectionMode` to `"manual"` or `"ui"`.
```ts
export default defineContentScript({
matches: ['*://google.com/*', '*://duckduckgo.com/*'],
cssInjectionMode: 'manual',
main(ctx) {
// ...
},
});
```
## UI
WXT provides a utility function, `createContentScriptUi` to simplify mounting a UI from a content script. Internally, it uses the `ShadowRoot` API to isolate your CSS from the webpages.
`createContentScriptUi` requires a `ContentScriptContext` so that when the context is invalidated, the UI is automatically removed from the webpage.
:::details When to use `createContentScriptUi`
You should only use `createContentScriptUi` if you want your UI's styles isolated from the webpages. If you want to create a more "integrated" UI that uses the page's styles, you can just use the regular JS API's to append your UI to the page.
```ts
const ui = document.createElement('div');
const anchor = document.querySelector('#anchor-selector');
anchor.append(ui);
```
:::
### Usage
To use `createContentScriptUi`, follow these steps:
1. Import your CSS file at the top of your content script
2. Set `cssInjectionMode: "ui"` inside `defineContentScript`
3. Call `createContentScriptUi`
4. Call `ui.mount()` to add the UI to the webpage
Here's a basic example:
```ts
// entrypoints/ui.content/index.ts
import './style.css';
export default defineContentScript({
// ...
cssInjectionMode: 'ui',
async main(ctx) {
const ui = await createContentScriptUi(ctx, {
name: 'example-ui',
type: 'inline',
anchor: '#some-element',
append: 'after',
mount(container) {
// Mount UI inside `container`...
},
});
// Yoy must call `mount` to add the UI to the page.
ui.mount();
},
});
```
If you're using a frontend framework, you'll also need to include an `onRemoved` callback:
:::code-group
```ts [Vue]
import { createApp } from 'vue';
createContentScriptUi(ctx, {
// ...
mount(container) {
// Create a new app and mount it inside the container
const app = createApp(...);
app.mount(container);
return app;
},
onRemove(app) {
// When the UI is removed from the DOM, call unmount to stop the app
app.unmount();
},
});
```
```ts [React]
import ReactDOM from 'react-dom/client';
createContentScriptUi(ctx, {
// ...
mount(container) {
// Create a root using the container and render your app
const root = ReactDOM.createRoot(container);
root.render(...);
return root;
},
onRemove(root) {
// When the UI is removed from the DOM, call unmount to stop the app
root.unmount();
},
});
```
```ts [Svelte]
import App from './App.svelte';
createContentScriptUi(ctx, {
// ...
mount(container) {
// Mount your app component inside the container
return new App({
target: container,
});
},
onRemove(app) {
// When the UI is removed from the DOM, call $destroy to stop the app
app.$destroy();
},
});
```
```ts [Solid]
import { render } from 'solid-js/web';
createContentScriptUi(ctx, {
// ...
mount(container) {
// Render your app component into the container
return render(() => ..., container)
},
onRemove(unmount) {
// When the UI is removed from the DOM, call unmount to stop the app
unmount();
},
});
```
:::
### `anchor`
The anchor dictates where the UI will be mounted.
### `append`
Customize where the UI get's appended to the DOM, relative to the `anchor` element.
### `type`
There are 3 types of UI's you can mount.
- `inline`: Shows up inline based on the `anchor` and `append` options
- `overlay`: Shows up inline, but styled to be 0px by 0px, with overflow visible. This causes the UI to overlay on top of the webpage's content
- `modal`: A fullscreen overlay that covers the entire screen, regardless of where it's anchored.
> TODO: Add visualization of the different UI types.
### Overlay `alignment`
Because the overlay UI type results in a 0px by 0px container being added to the webpage, the `alignment` option allows you to configure which corner of your UI is aligned with the 0x0 element.
> TODO: Add visualization of the different alignments.
@@ -2,10 +2,10 @@
WXT can build CSS entrypoints individually. CSS entrypoints are always unlisted.
See [Content Script CSS](/guide/content-scripts.md#css) documentation for the recomended approach to include CSS with a content script.
See [Content Script CSS](/entrypoints/content-scripts#css) documentation for the recomended approach to include CSS with a content script.
:::info
If the recommended approach doesn't work for your use case, you can use any of the filename patterns below to build the styles separate from the JS and use the [`transformManifest` hook](/config.md#transformmanifest) to manually add your CSS file to the manifest.
If the recommended approach doesn't work for your use case, you can use any of the filename patterns below to build the styles separate from the JS and use the [`transformManifest` hook](/api/config#transformmanifest) to manually add your CSS file to the manifest.
:::
## Filenames
@@ -6,8 +6,8 @@ TypeScript files that are built, but are not included in the manifest.
<EntrypointPatterns
:patterns="[
['<name>.(ts|tsx)', '<name>.js'],
['<name>/index.(ts|tsx)', '<name>.js'],
['<name>.[jt]sx?', '<name>.js'],
['<name>/index.[jt]sx?', '<name>.js'],
]"
/>
-46
View File
@@ -1,46 +0,0 @@
# Build Targets
You can build an extension for any combination of browser and manifest verison. Different browsers and manifest versions support different APIs and entrypoints, so be sure to check that your extension functions as expected for each target.
Separate build targets are written to their own output directories:
```
<rootDir>
└─ .output
├─ chrome-mv3
├─ firefox-mv2
├─ edge-mv3
└─ ...
```
## Target Browser
To build for a specific browser, pass the `-b --browser` flag from the CLI:
```
wxt --browser firefox
wxt build --browser firefox
```
By default, it will build for `chrome`. When excluding the [`--mv2` or `--mv3` flags](#target-manifest-version), it will default to the commonly accepted manifest version used with that browser.
| Browser | Default Manifest Version |
| ---------------- | :----------------------: |
| `chrome` | 3 |
| `firefox` | 2 |
| `safari` | 2 |
| `edge` | 3 |
| Any other string | 3 |
## Target Manifest Version
To build for a specific manifest version, pass either the `--mv2` flag or `--mv3` flag from the CLI.
```sh
wxt --mv2
wxt build --mv2
```
When the `-b --browser` flag is not passed, it defaults to `chrome`. So here, we're targetting MV2 for Chrome.
-5
View File
@@ -1,5 +0,0 @@
# Testing
:::warning 🚧&ensp;Testing utils are not implemented yet!
Eventually, the plan is to have an integration with Vitest.
:::
+6 -5
View File
@@ -3,18 +3,19 @@
WXT uses the same tool as Nuxt for auto-imports, [`unimport`](https://github.com/unjs/unimport).
:::info Testing
To setup your test environment for auto-imports, see [Testing](/get-started/testing.md).
To setup your test environment for auto-imports, see [Testing](/guide/testing).
:::
## WXT Auto-imports
Some WXT APIs can be used without importing them:
- [`browser`](/config.md#browser) from `wxt/browser`, a small wrapper around `webextension-polyfill`
- [`defineContentScript`](/config.md#defiencontentscript) from `wxt/client`
- [`defineBackground`](/config.md#definebackgroundscript) from `wxt/client`
- [`browser`](/api/wxt-browser#browser) from `wxt/browser`, a small wrapper around `webextension-polyfill`
- [`defineContentScript`](/api/wxt-client#defiencontentscript) from `wxt/client`
- [`defineBackground`](/api/wxt-client#definebackgroundscript) from `wxt/client`
- [`createContentScriptUi`](/api/wxt-client#createcontentscriptui) from `wxt/client`
And more. All [`wxt/client`](/config.md#wxtclient) APIs can be used without imports.
And more. All [`wxt/client`](/api/wxt-client) APIs can be used without imports.
## Project Auto-imports
@@ -15,7 +15,7 @@ export default defineConfig({
```
:::info
See the [Config reference](/config.md) for a full list of options.
See the [Config reference](/api/config) for a full list of options.
:::
## Directory Config
@@ -25,7 +25,7 @@ WXT allows you to edit several directories to your liking:
- `root` (default: `process.cwd()`) - Root of the WXT project
- `srcDir` (default: `<rootDir>`) - Location of all your source code
- `entrypointsDir` (default: `<srcDir>/entrypoints`) - Folder containing all the entrypoints.
- `publicDir` (default: `<srcDir>/public`) - Folder containing [public assets](/get-started/assets.md)
- `publicDir` (default: `<srcDir>/public`) - Folder containing [public assets](/guide/assets)
### Example
-85
View File
@@ -1,85 +0,0 @@
# Content Scripts
[Chrome Docs](https://developer.chrome.com/docs/extensions/mv3/content_scripts/) &bull; [Firefox Docs](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts)
When creating content script entrypoints, they are automatically included in the `manifest.json` along with any CSS files they import.
## Filenames
<EntrypointPatterns
:patterns="[
['content.(ts|tsx)', 'content-scripts/content.js'],
['content/index.(ts|tsx)', 'content-scripts/content.js'],
['<name>.content.(ts|tsx)', 'content-scripts/<name>.js'],
['<name>.content/index.(ts|tsx)', 'content-scripts/<name>.js'],
]"
/>
## Definition
```ts
export default defineContentScript({
// Set manifest options
matches: ['*://google.com/*', '*://duckduckgo.com/*'],
excludeMatches: undefined | [],
includeGlobs: undefined | [],
excludeGlobs: undefined | [],
allFrames: undefined | [],
runAt: undefined | 'document_start' | 'document_end' | 'document_idle',
matchAboutBlank: undefined | true | false,
matchOriginAsFallback: undefined | true | false,
world: undefined | 'ISOLATED' | 'MAIN',
// Set include/exclude if the background should be removed from some builds
include: undefined | string[],
exclude: undefined | string[],
main() {
// Executed when content script is loaded
},
});
```
> All manifest options default to `undefined`.
When defining multiple content scripts, content script entrypoints that have the same set of options will be merged into a single `content_script` item in the manifest.
## CSS
To include CSS with your content script, import the CSS file at the top of your entrypoint.
```
<srcDir>
└─ entrypoints/
└─ overlay.content/
├─ index.ts
└─ style.css
```
```ts
// entrypoints/overlay.content/index.ts
import './style.css';
export default defineContentScript({
matches: ['*://google.com/*', '*://duckduckgo.com/*'],
main() {
// ...
},
});
```
Any styles imported in your content script will be added to that content script's `css` array in your `manifest.json`:
```json
// .output/chrome-mv3/manifest.json
{
"content_scripts": [
{
"matches": ["*://google.com/*", "*://duckduckgo.com/*"],
"js": ["content-scripts/overlay.js"],
"css": ["content-scripts/overlay.css"]
}
]
}
```
+53
View File
@@ -0,0 +1,53 @@
# Development
WXT's main goal is providing the best DX it possibly can. When running your extension in dev mode, each part of your extension is reloaded separately when possible.
| | HMR | Reloaded individually | Reload extension | Restart browser |
| ------------------- | :-: | :-------------------: | :--------------: | :----------------------------------------------------: |
| HTML File | | ✅ |
| HTML Dependency | ✅ |
| MV3 Content Script | | ✅ |
| MV2 Content Script | | | ✅ |
| Background | | | ✅ |
| manifest.json | | | | 🟡 See [#16](https://github.com/wxt-dev/wxt/issues/16) |
| `wxt.config.ts` | | | | 🟡 See [#10](https://github.com/wxt-dev/wxt/issues/10) |
| `web-ext.config.ts` | | | | 🟡 See [#10](https://github.com/wxt-dev/wxt/issues/10) |
## Configure Browser Startup
WXT uses [`web-ext` by Mozilla](https://github.com/mozilla/web-ext) to automatically open a browser with the extension installed. You can configure the runner's behavior via the [`runner`](/api/config#runner.disabled) option, or in a separate gitignored file, `web-ext.config.ts`.
:::code-group
```ts [wxt.config.ts]
import { defineConfig } from 'wxt';
export default defineConfig({
runner: {
// Runner config
},
});
```
```ts [web-ext.config.ts]
import { defineRunnerConfig } from 'wxt';
export default defineRunnerConfig({
// Runner config
});
```
:::
You may also setup default for your entire computer by creating a `web-ext.config.ts` file in your home directory. This is useful if you want to specify config for all project on your computer, like that you want to use Chrome Beta instead of Chrome.
```ts
// ~/web-ext.config.ts
import { defineRunnerConfig } from 'wxt';
export default defineRunnerConfig({
binaries: {
chrome: '/path/to/chrome-beta',
},
});
```
@@ -42,7 +42,7 @@ would result in the following `manifest.json`:
}
```
If a file uses a [special name recognized by WXT](/get-started/entrypoints.md), it will be added to the manifest. In this case:
If a file uses a special name recognized by WXT, it will be added to the manifest. In this case:
- `popup.html` &rarr; `action.default_popup`
- `content.ts` &rarr; `content_scripts.0.js.0`
@@ -53,7 +53,7 @@ But not all entrypoints are added to the `manifest.json`. If the filename is not
In this case, `injected.ts` gets output to `<outdir>/injected.js` and is accessible via `browser.runtime.getURL("/injected.js")`.
:::info
See [`/entrypoints` folder](/guide/background.md) documentation for a full list of recognized entrypoint filenames.
See [`/entrypoints` folder](/entrypoints/background) documentation for a full list of recognized entrypoint filenames.
:::
## Entrypoint Options
@@ -84,5 +84,5 @@ export default defineContentScript({
```
:::info
For a full list of entrypoints and each of their options, see the [`/entrypoints` folder](/guide/background.md) documentation.
For a full list of entrypoints and each of their options, see the [`/entrypoints` folder](/entrypoints/background) documentation.
:::
+2 -2
View File
@@ -11,10 +11,10 @@ And that's it! Your extension now supports Chrome, Firefox, Safari, Edge, and ot
## Basic Usage
The `browser` variable is available globally via [auto-imports](/guide/auto-imports.md), or it can be imported manually.
The `browser` variable is available globally via [auto-imports](/guide/auto-imports), or it can be imported manually.
```ts
import browser from 'wxt/browser';
import { browser } from 'wxt/browser';
```
The `wxt/browser` module exports a customized version of `webextension-polyfill`'s browser with improved typing.
@@ -1,12 +1,6 @@
# Installation
Bootstrap a new project, start from scratch, or migrate an existing project.
:::warning 🚧&ensp;WSL Support
**_WXT does not support [Windows Subsystem for Linux](https://learn.microsoft.com/en-us/windows/wsl/) yet_**. See [Issue #55](https://github.com/wxt-dev/wxt/issues/55) to track progress.
In the meantime, you can use `cmd` instead.
:::
Bootstrap a new project, start from scratch, or [migrate an existing project](/guide/migrate-to-wxt).
## Bootstrap Project
@@ -32,7 +26,9 @@ There are several starting templates available.
| <Icon name="Svelte" /> [`svelte`](https://github.com/wxt-dev/wxt/tree/main/templates/svelte) |
| <Icon name="Solid" icon="https://www.solidjs.com/img/favicons/favicon-32x32.png" /> [`solid`](https://github.com/wxt-dev/wxt/tree/main/templates/solid) |
> All templates are in TypeScript. WXT does not support JS at this time.
:::info
All templates default to TypeScript. Rename the file extensions to `.js` to use JavaScript instead.
:::
## From Scratch
@@ -148,6 +144,6 @@ If you're an experienced web extension developer and think the dev manifest look
You're ready to build your web extension!
- Learn how to [add entrypoints](./entrypoints.md) like the popup, options page, or content scripts
- [Configure WXT](./configuration.md) by creating a `wxt.config.ts` file
- Learn how to [add entrypoints](./entrypoints) like the popup, options page, or content scripts
- [Configure WXT](./configuration) by creating a `wxt.config.ts` file
- Checkout [example projects](https://github.com/wxt-dev/wxt-examples) to see how to perfom common tasks with WXT
@@ -1,3 +1,10 @@
---
head:
- - link
- rel: canonical
href: https://wxt.dev
---
# Introduction
WXT is a free and open source framework for building web extensions in an conventional, intuative, and safe way **_for all browsers_**.
@@ -28,5 +35,5 @@ Production builds are optimized for store review, changing as few files as possi
In addition, WXT fully supports Firefox's source code requirements when using a bundler. It will automatically create and upload a ZIP file of your source code.
:::info
See [Publishing](./publishing.md) for more info around production builds.
See [Publishing](./publishing) for more info around production builds.
:::
+2 -2
View File
@@ -49,7 +49,7 @@ The [manifest's `version` and `version_name`](https://developer.chrome.com/docs/
## `icons`
By default, WXT will discover icons in your [`public` directory](/get-started/assets#public-directory) and use them for the [manifest's `icons`](https://developer.chrome.com/docs/extensions/mv3/manifest/icons/).
By default, WXT will discover icons in your [`public` directory](/guide/assets#public-directory) and use them for the [manifest's `icons`](https://developer.chrome.com/docs/extensions/mv3/manifest/icons/).
```
public/
@@ -94,7 +94,7 @@ export default defineConfig({
## Localization
Similar to the icon, the [`_locales` directory](https://developer.chrome.com/docs/extensions/reference/i18n/) should be placed inside the the WXT's [`public` directory](/get-started/assets#public-directory).
Similar to the icon, the [`_locales` directory](https://developer.chrome.com/docs/extensions/reference/i18n/) should be placed inside the the WXT's [`public` directory](/guide/assets#public-directory).
```
public/
+57
View File
@@ -0,0 +1,57 @@
---
outline: deep
---
# Migrate to WXT
> If you have problems migrating to WXT, feel free to ask for help in GitHub by [starting a discussion](https://github.com/wxt-dev/wxt/discussions/new?category=q-a)!
## Overview
Always start by generating a new vanilla project and merging it into your project one file at a time.
```sh
cd path/to/your/project
pnpx wxt@latest init example-wxt --template vanilla
```
In general, you'll need to:
<input type="checkbox" /> Install `wxt`<br />
<input type="checkbox" /> Update/create `package.json` scripts to use `wxt` (don't forget about `postinstall`)<br />
<input type="checkbox" /> Move entrypoints into `entrypoints/` directory<br />
<input type="checkbox" /> Move assets into either the `assets/` or `public/` directories<br />
<input type="checkbox" /> Move manifest.json content into `wxt.config.ts`<br />
<input type="checkbox" /> Convert custom import syntax to be compatible with Vite<br />
<input type="checkbox" /> Add a default export to JS entrypoints<br />
<input type="checkbox" /> Use the `browser` global instead of `chrome`<br />
<input type="checkbox" /> Compare final `manifest.json` files, making sure permissions and host permissions are unchanged<br />
<input type="checkbox" /> Extension output by `wxt build` works the same way as before the migration<br />
Every project is different, so there's no one-solution-fits-all to migrating your project. Just make sure `wxt dev` runs, `wxt build` results in a working extension, and the list of permissions in the `manifest.json` hasn't changed. If all that looks good, you've finished migrating your extension!
## Popular Tools/Frameworks
Here's specific steps for other popuplar frameworks/build tools.
### `vite-plugin-web-extension`
Since you're already using Vite, it's a simple refactor.
1. Install `wxt`
2. Move and refactor your entrypoints to WXT's style (with a default export)
3. Update package.json scripts to use `wxt`
4. Add `"postinstall": "wxt prepare"` script
5. Move the `manifest.json` into `wxt.config.ts`
6. Move any custom settings from `vite.config.ts` into `wxt.config.ts`'s
7. Compare `dist/manifest.json` to `.output/*/manifest.json`, they should have the same content as before. If not, tweak your entrypoints and config to get as close as possible.
### `plasmo`
1. Install `wxt`
2. Move entrypoints into `entrypoints/` directory, merging the named exports used to configure your JS entrypoints into WXT's default export
3. Move public `assets/*` into the `public/` directory
4. If you use CSUI, migrate to WXT's `createContentScriptUi`
5. Convert Plasmo's custom import resolutions to Vite's
6. If importing remote code via a URL, add a `url:` prefix so it works with WXT
7. Compare your output `manifest.json` files from before the migration to after the migration. They should have the same content. If not, tweak your entrypoints and config to get as close as possible.
+110
View File
@@ -0,0 +1,110 @@
# Multiple Browsers
You can build an extension for any combination of browser and manifest verison. Different browsers and manifest versions support different APIs and entrypoints, so be sure to check that your extension functions as expected for each target.
Separate build targets are written to their own output directories:
```
<rootDir>
└─ .output
├─ chrome-mv3
├─ firefox-mv2
├─ edge-mv3
└─ ...
```
## Target Browser
To build for a specific browser, pass the `-b --browser` flag from the CLI:
```
wxt --browser firefox
wxt build --browser firefox
```
By default, it will build for `chrome`. When excluding the [`--mv2` or `--mv3` flags](#target-manifest-version), it will default to the commonly accepted manifest version used with that browser.
| Browser | Default Manifest Version |
| ---------------- | :----------------------: |
| `chrome` | 3 |
| `firefox` | 2 |
| `safari` | 2 |
| `edge` | 3 |
| Any other string | 3 |
## Target Manifest Version
To build for a specific manifest version, pass either the `--mv2` flag or `--mv3` flag from the CLI.
```sh
wxt --mv2
wxt build --mv2
```
When the `-b --browser` flag is not passed, it defaults to `chrome`. So here, we're targetting MV2 for Chrome.
## Customizing Entrypoints
There are several ways to customize entrypoint definitions per browser.
First, you can use either the `include` or `exclude` option to include or exclude the entrypoint from specific browsers. Here are some examples
:::code-group
```ts [Background]
export default defineBackground({
// Only include a background script when targeting chrome
include: ['chrome'],
});
```
```ts [Content Script]
export default defineContentScript({
// Do not add this content script to the manifest when targeting firefox
exclude: ['firefox'],
});
```
```html [HTML page]
<!-- entrypoints/options.html -->
<html>
<head>
<!-- Don't include the options page for safari -->
<meta name="manifest.exclude" content="['safari']" />
</head>
</html>
```
:::
Second, you can change individual options per-browser:
:::code-group
```ts [Background]
export default defineBackground({
persistent: {
// Use a non-persistent background script for just safari
safari: false,
},
});
```
```ts [Content Script]
export default defineContentScript({
matches: {
// Run the content script on different pages for each browser
chrome: ['*://*.google.com/*'],
firefox: ['*://*.duckduckgo.com/*'],
edge: ['*://*.bing.com/*'],
},
});
```
:::
:::warning
Only `defineBackground` and `defineContentScript` support per-browser options right now.
:::
+92
View File
@@ -0,0 +1,92 @@
# Testing
WXT provides a couple of utils for unit testing your extension.
[[toc]]
## Fake Browser
The `wxt/fake-browser` package includes an in-memory implementation of the `browser` variable you can use for testing. WXT simply re-exports the `fakeBrowser` variable from [`@webext-core/fake-browser`](https://webext-core.aklinker1.io/guide/fake-browser/).
Here's an example test using Vitest:
```ts
import { describe, it, expect, vi } from 'vitest';
import { browser } from 'wxt/browser';
import { fakeBrowser } from 'wxt';
// Function we're testing
function onHelloMessage(cb: () => void) {
browser.runtime.onMessage.addEventListener((message) => {
if (message.type === 'hello') return 'world';
});
}
// Mock the real `browser` object with a fake one
vi.mock('wxt/browser', () => import('wxt/fake-browser'));
describe('onHelloMessage', () => {
it("should call the callback when the message type is 'hello'", () => {
const cb = vi.fn();
const expected = 'world';
onHelloMessage(cb);
const actual = await fakeBrowser.runtime.sendMessage({ type: 'hello' });
expect(cb).toBeCalledTimes(1);
expect(actual).toBe(expected);
});
it("should ignore the message when the message type is not 'hello'", () => {
const cb = vi.fn();
onHelloMessage(cb);
await fakeBrowser.runtime.sendMessage({ type: 'not-hello' }).catch();
expect(cb).not.toBeCalled();
});
});
```
See [`@webext-core/fake-browser`](https://webext-core.aklinker1.io/guide/fake-browser/) for setup, implemented APIs, and example tests.
## Handling Auto-imports
By default, WXT uses auto-imports. For tests, this can cause issues if your test environment is not setup to handle them correctly.
:::warning 🚧&ensp;Testing utils are not implemented yet!
Eventually, WXT will provide utilities for setting up these auto-imports. For now, you'll need to set them up manually.
:::
Not all testing frameworks can handle auto-imports. If your framework or setup is not listed below, it may be easiest to disable auto-imports.
To setup auto-imports manually, use [`unplugin-auto-import`](https://www.npmjs.com/package/unplugin-auto-import). It uses the same tool, `unimport`, as WXT and will result in compatiple auto-imports. `unplugin-auto-import` supports lots of different tools (vite, webpack, esbuild, rollup, etc). You can try and integrate it into your build process.
### Vitest (Recommended)
Vitest is easy, simply add `uplugin-auto-import` to your project.
```ts
// vitest.config.ts
import autoImports from 'unplugin-auto-import/vite';
export default defineConfig({
plugins: [
autoImports({
imports: [{ name: 'defineConfig', from: 'wxt' }],
presets: [{ package: 'wxt/client' }, { package: 'wxt/browser' }],
dirs: ['components', 'composables', 'hooks', 'utils'],
}),
],
});
```
### Jest
Don't use jest and auto-imports. You could try and configure jest to be transpiled by one of `unplugin-auto-import`'s supported built tools, but I don't know of a way to configure this. See [unplugin/unplugin-auto-import#33](https://github.com/unplugin/unplugin-auto-import/issues/33) if you want to try and set it up.
I would recommend disabling auto-imports or migrating to Vitest if you want to use auto-imports.
### Mocha
TODO: Is this possible? Maybe with `esbuild-mocha`? I would recommend moving to Vitest.
+4 -4
View File
@@ -10,9 +10,9 @@ All of Vite's config can be customized by setting the `vite` configuration in yo
import { defineConfig } from 'wxt';
export default defineConfig({
vite: {
vite: () => ({
// Same as `defineConfig({ ... })` inside vite.config.ts
},
}),
});
```
@@ -26,10 +26,10 @@ All plugins should work in WXT, but it is worth pointing out that since WXT orch
import { defineConfig } from 'wxt';
export default defineConfig({
vite: {
vite: () => ({
plugins: [
// ...
],
},
}),
});
```
+55 -15
View File
@@ -1,57 +1,97 @@
---
# https://vitepress.dev/reference/default-theme-home-page
layout: home
titleTemplate: 'Next Generation Web Extension Framework'
title: Next-gen Web Extension Framework
hero:
name: WXT
text: Next-gen Web Extension Framework
tagline: Powered by Vite, inspired by Nuxt.
tagline: An open source tool that makes Chrome Extension devlopment faster than ever before.
image:
src: /hero-logo.svg
alt: WXT
actions:
- theme: brand
text: Get Started
link: /get-started/installation
link: /guide/installation
- theme: alt
text: Learn More
link: /get-started/introduction
link: /guide/introduction
features:
- icon: 🌐
title: Supported Browsers
details: Chrome, Firefox, Edge, Safari, and any Chromium based browser.
details: WXT will build extensions for Chrome, Firefox, Edge, Safari, and any Chromium based browser.
link: /guide/multiple-browsers
linkText: Read docs
- icon: ✅
title: MV2 and MV3
details: Supports both manifest versions for each browser.
details: Build Manifest V2 or V3 extensions for any browser using the same codebase.
link: /guide/multiple-browsers#target-manifest-version
linkText: Read docs
- icon: ⚡
title: Fast Dev Mode
details: HMR for UIs and fast reload for background and content scripts.
details: Lighting fast HMR for UI development and fast reloads for content/background scripts enables faster iterations.
link: /guide/development.html
linkText: Learn more
- icon: 📂
title: File Based Entrypoints
details: Manifest is generated based on files inside the project.
details: Manifest is generated based on files in the project with inline configuration.
link: /guide/entrypoints
linkText: See project structure
- icon: 🚔
title: TypeScript
details: Scale projects with full TS support.
details: Create large projects with confidence using TS by default.
- icon: 🦾
title: Auto-imports
details: Nuxt-like auto-imports to speed up development.
link: /guide/auto-imports
linkText: Read docs
- icon: ⬇️
title: Bundle Remote Code
details: Downloads and bundles remote code imported from URLs.
link: /guide/remote-code
linkText: Read docs
- icon: 🎨
title: Frontend Framework Agnostic
details: Works with any front-end framework with a Vite plugin.
link: /guide/configuration#frontend-frameworks
linkText: Add a framework
- icon: 🖍️
title: Bootstrap a New Project
details: Comes with starter templates for all major frontend frameworks.
- icon: 🤖
title: Automated Publishing
details: 'TODO: Automatically zip, upload, and release extensions.'
details: Get started quickly with several awesome project templates.
link: /guide/installation#bootstrap-project
linkText: See templates
- icon: 📏
title: Bundle Analysis
details: 'TODO: Tools for analyizing the final extension bundle.'
details: Tools for analyizing the final extension bundle and minimizing your extension's size.
- icon: 🤖
title: Automated Publishing
details: 'Coming soon. Automatically zip, upload, and release extensions.'
---
<UsingWxtSection />
<section class="vp-doc">
<div class="container">
<h2>Put <span style="color: var(--vp-c-brand-1)">Developer Experience</span> First</h2>
<p>
WXT's simplifies the chrome extension development process by providing tools for zipping and publishing, the best-in-class dev mode, an opinionated project structure, and more. Iterate faster, develop features not build scripts, and use everything the JS ecosystem has to offer.
</p>
<div style="margin: auto; width: 100%; max-width: 700px; text-align: center">
<img src="./assets/cli-output.png" alt="Screenshot of WXT's build output" />
<small>
And who doesn't appreciate a beautiful CLI?
</small>
</div>
</div>
</section>
<ClientOnly>
<UsingWxtSection />
</ClientOnly>
<style scoped>
.container {
margin: 0 auto;
max-width: 1152px;
}
</style>
+30
View File
@@ -0,0 +1,30 @@
# Netlify Redirects File
# https://docs.netlify.com/routing/redirects/
# Old URLs -> New URLs
/config.html /api/config.html
/entrypoints /entrypoints/background.html
/get-started/assets.html /guide/assets.html
/get-started/build-targets.html /guide/multiple-browsers.html
/get-started/compare.html /guide/compare.html
/get-started/configuration.html /guide/configuration.html
/get-started/entrypoints.html /guide/entrypoints.html
/get-started/installation.html /guide/installation.html
/get-started/introduction.html /guide/introduction.html
/get-started/publishing.html /guide/publishing.html
/get-started/testing.html /guide/testing.html
/guide/background.html /entrypoints/background.html
/guide/bookmarks.html /entrypoints/bookmarks.html
/guide/content-scripts.html /entrypoints/content-scripts.html
/guide/css.html /entrypoints/css.html
/guide/devtools.html /entrypoints/devtools.html
/guide/history.html /entrypoints/history.html
/guide/manifest.html /entrypoints/manifest.html
/guide/newtab.html /entrypoints/newtab.html
/guide/options.html /entrypoints/options.html
/guide/popup.html /entrypoints/popup.html
/guide/sandbox.html /entrypoints/sandbox.html
/guide/sidepanel.html /entrypoints/sidepanel.html
/guide/unlisted-pages.html /entrypoints/unlisted-pages.html
/guide/unlisted-scripts.html /entrypoints/unlisted-scripts.html
/guide/build-targets.html /guide/multiple-browsers.html
+5
View File
@@ -0,0 +1,5 @@
User-agent: *
Disallow: /api.html
Disallow: /config.html
Sitemap: https://wxt.dev/sitemap.xml
+2 -1
View File
@@ -16,11 +16,12 @@ describe('Auto Imports', () => {
// Generated by wxt
export {}
declare global {
const ContentScriptContext: typeof import('wxt/client')['ContentScriptContext']
const browser: typeof import('wxt/browser')['browser']
const createContentScriptUi: typeof import('wxt/client')['createContentScriptUi']
const defineBackground: typeof import('wxt/client')['defineBackground']
const defineConfig: typeof import('wxt')['defineConfig']
const defineContentScript: typeof import('wxt/client')['defineContentScript']
const mountContentScriptUi: typeof import('wxt/client')['mountContentScriptUi']
}
"
`);
+1 -1
View File
@@ -40,5 +40,5 @@ describe('Init command', () => {
"wxt.config.ts",
]
`);
}, 30e3);
});
});
+305 -74
View File
@@ -193,117 +193,348 @@ describe('Manifest Content', () => {
});
});
it('should group content scripts and styles together based on their matches and run_at', async () => {
const project = new TestProject();
project.addFile(
'entrypoints/one.content/index.ts',
`import "./style.css";
describe('content_scripts', () => {
it('should group content scripts and styles together based on their matches and run_at', async () => {
const project = new TestProject();
project.addFile(
'entrypoints/one.content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["*://google.com/*"],
main: () => {},
})`,
);
project.addFile('entrypoints/one.content/style.css', `body { color: red }`);
project.addFile(
'entrypoints/two.content/index.ts',
`import "./style.css";
);
project.addFile(
'entrypoints/one.content/style.css',
`body { color: red }`,
);
project.addFile(
'entrypoints/two.content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["*://google.com/*"],
runAt: "document_end",
main: () => {},
})`,
);
project.addFile(
'entrypoints/two.content/style.css',
`body { color: green }`,
);
project.addFile(
'entrypoints/three.content/index.ts',
`import "./style.css";
);
project.addFile(
'entrypoints/two.content/style.css',
`body { color: green }`,
);
project.addFile(
'entrypoints/three.content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["*://google.com/*"],
runAt: "document_end",
main: () => {},
})`,
);
project.addFile(
'entrypoints/three.content/style.css',
`body { color: blue }`,
);
project.addFile(
'entrypoints/four.content/index.ts',
`import "./style.css";
);
project.addFile(
'entrypoints/three.content/style.css',
`body { color: blue }`,
);
project.addFile(
'entrypoints/four.content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["*://duckduckgo.com/*"],
runAt: "document_end",
main: () => {},
})`,
);
project.addFile(
'entrypoints/four.content/style.css',
`body { color: yellow }`,
);
);
project.addFile(
'entrypoints/four.content/style.css',
`body { color: yellow }`,
);
await project.build();
await project.build();
const manifest = await project.getOutputManifest();
const manifest = await project.getOutputManifest();
expect(manifest.content_scripts).toContainEqual({
matches: ['*://duckduckgo.com/*'],
run_at: 'document_end',
css: ['assets/four.css'],
js: ['content-scripts/four.js'],
expect(manifest.content_scripts).toContainEqual({
matches: ['*://duckduckgo.com/*'],
run_at: 'document_end',
css: ['content-scripts/four.css'],
js: ['content-scripts/four.js'],
});
expect(manifest.content_scripts).toContainEqual({
matches: ['*://google.com/*'],
run_at: 'document_end',
css: ['content-scripts/three.css', 'content-scripts/two.css'],
js: ['content-scripts/three.js', 'content-scripts/two.js'],
});
expect(manifest.content_scripts).toContainEqual({
matches: ['*://google.com/*'],
css: ['content-scripts/one.css'],
js: ['content-scripts/one.js'],
});
});
expect(manifest.content_scripts).toContainEqual({
matches: ['*://google.com/*'],
run_at: 'document_end',
css: ['assets/three.css', 'assets/two.css'],
js: ['content-scripts/three.js', 'content-scripts/two.js'],
});
expect(manifest.content_scripts).toContainEqual({
matches: ['*://google.com/*'],
css: ['assets/one.css'],
js: ['content-scripts/one.js'],
});
});
it('should add to any content scripts declared in wxt.config.ts', async () => {
const project = new TestProject();
project.addFile(
'entrypoints/one.content/index.ts',
`export default defineContentScript({
it('should add to any content scripts declared in wxt.config.ts', async () => {
const project = new TestProject();
project.addFile(
'entrypoints/one.content/index.ts',
`export default defineContentScript({
matches: ["*://google.com/*"],
main: () => {},
})`,
);
project.addFile(
'entrypoints/two.content/style.css',
`body {
);
project.addFile(
'entrypoints/two.content/style.css',
`body {
background-color: red;
}`,
);
project.setConfigFileConfig({
manifest: {
content_scripts: [
{
css: ['content-scripts/two.css'],
matches: ['*://*.google.com/*'],
},
],
},
});
await project.build();
const manifest = await project.getOutputManifest();
expect(manifest.content_scripts).toContainEqual({
css: ['content-scripts/two.css'],
matches: ['*://*.google.com/*'],
});
expect(manifest.content_scripts).toContainEqual({
matches: ['*://google.com/*'],
js: ['content-scripts/one.js'],
});
});
it('should add a CSS entry when cssInjectionMode is undefined', async () => {
const project = new TestProject();
project.addFile(
'entrypoints/content/style.css',
'body { background-color: red; }',
);
project.addFile(
'entrypoints/content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["https://*.google.com/*"],
main() {},
});`,
);
await project.build();
expect(await project.serializeFile('.output/chrome-mv3/manifest.json'))
.toMatchInlineSnapshot(`
".output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"content_scripts\\":[{\\"matches\\":[\\"https://*.google.com/*\\"],\\"css\\":[\\"content-scripts/content.css\\"],\\"js\\":[\\"content-scripts/content.js\\"]}]}"
`);
});
it('should add a CSS entry when cssInjectionMode is "manifest"', async () => {
const project = new TestProject();
project.addFile(
'entrypoints/content/style.css',
'body { background-color: red; }',
);
project.addFile(
'entrypoints/content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["https://*.google.com/*"],
cssInjectionMode: "manifest",
main() {},
});`,
);
await project.build();
expect(await project.serializeFile('.output/chrome-mv3/manifest.json'))
.toMatchInlineSnapshot(`
".output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"content_scripts\\":[{\\"matches\\":[\\"https://*.google.com/*\\"],\\"css\\":[\\"content-scripts/content.css\\"],\\"js\\":[\\"content-scripts/content.js\\"]}]}"
`);
});
it('should not add an entry for CSS when cssInjectionMode is "manual"', async () => {
const project = new TestProject();
project.addFile(
'entrypoints/content/style.css',
'body { background-color: red; }',
);
project.addFile(
'entrypoints/content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["https://*.google.com/*"],
cssInjectionMode: "manual",
main() {},
});`,
);
await project.build();
expect(await project.serializeFile('.output/chrome-mv3/manifest.json'))
.toMatchInlineSnapshot(`
".output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"content_scripts\\":[{\\"matches\\":[\\"https://*.google.com/*\\"],\\"js\\":[\\"content-scripts/content.js\\"]}]}"
`);
});
it('should not add a content script entry for CSS when cssInjectionMode is "ui", but add a web_accessible_resources entry for MV2', async () => {
const project = new TestProject();
project.addFile(
'entrypoints/content/style.css',
'body { background-color: red; }',
);
project.addFile(
'entrypoints/content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["https://*.google.com/*"],
cssInjectionMode: "ui",
main() {},
});`,
);
await project.build({
manifestVersion: 2,
});
expect(await project.serializeFile('.output/chrome-mv2/manifest.json'))
.toMatchInlineSnapshot(`
".output/chrome-mv2/manifest.json
----------------------------------------
{\\"manifest_version\\":2,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"content_scripts\\":[{\\"matches\\":[\\"https://*.google.com/*\\"],\\"js\\":[\\"content-scripts/content.js\\"]}],\\"web_accessible_resources\\":[\\"content-scripts/content.css\\"]}"
`);
});
it('should not add a content script entry for CSS when cssInjectionMode is "ui", but add a web_accessible_resources entry for MV3', async () => {
const project = new TestProject();
project.addFile(
'entrypoints/content/style.css',
'body { background-color: red; }',
);
project.addFile(
'entrypoints/content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["https://*.google.com/*"],
cssInjectionMode: "ui",
main() {},
});`,
);
await project.build({
manifestVersion: 3,
});
expect(await project.serializeFile('.output/chrome-mv3/manifest.json'))
.toMatchInlineSnapshot(`
".output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"content_scripts\\":[{\\"matches\\":[\\"https://*.google.com/*\\"],\\"js\\":[\\"content-scripts/content.js\\"]}],\\"web_accessible_resources\\":[{\\"resources\\":[\\"content-scripts/content.css\\"],\\"matches\\":[\\"https://*.google.com/*\\"]}]}"
`);
});
});
it('should combine web accessible resources', async () => {
const project = new TestProject();
project.addFile(
'entrypoints/content/style.css',
'body { background-color: red; }',
);
project.addFile(
'entrypoints/content/index.ts',
`import "./style.css";
export default defineContentScript({
matches: ["https://*.google.com/*"],
cssInjectionMode: "ui",
main() {},
});`,
);
project.setConfigFileConfig({
manifest: {
content_scripts: [
{
css: ['content-scripts/two.css'],
matches: ['*://*.google.com/*'],
},
web_accessible_resources: [
{ resources: ['one.png'], matches: ['https://one.com/*'] },
],
},
});
await project.build();
expect(await project.serializeFile('.output/chrome-mv3/manifest.json'))
.toMatchInlineSnapshot(`
".output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"web_accessible_resources\\":[{\\"resources\\":[\\"one.png\\"],\\"matches\\":[\\"https://one.com/*\\"]},{\\"resources\\":[\\"content-scripts/content.css\\"],\\"matches\\":[\\"https://*.google.com/*\\"]}],\\"content_scripts\\":[{\\"matches\\":[\\"https://*.google.com/*\\"],\\"js\\":[\\"content-scripts/content.js\\"]}]}"
`);
});
it('should respect the transformManifest option', async () => {
const project = new TestProject();
project.addFile(
'wxt.config.ts',
`import { defineConfig } from 'wxt';
export default defineConfig({
transformManifest(manifest) {
manifest.author = "Custom Author"
}
})`,
);
await project.build();
const manifest = await project.getOutputManifest();
expect(manifest.content_scripts).toContainEqual({
css: ['content-scripts/two.css'],
matches: ['*://*.google.com/*'],
});
expect(manifest.content_scripts).toContainEqual({
matches: ['*://google.com/*'],
js: ['content-scripts/one.js'],
});
const output = await project.serializeFile(
'.output/chrome-mv3/manifest.json',
);
expect(output).toMatchInlineSnapshot(`
".output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"author\\":\\"Custom Author\\"}"
`);
});
it.each([
{ browser: undefined, outDir: 'chrome-mv3', expected: undefined },
{ browser: 'chrome', outDir: 'chrome-mv3', expected: undefined },
{ browser: 'firefox', outDir: 'firefox-mv2', expected: true },
{ browser: 'safari', outDir: 'safari-mv2', expected: false },
])(
'should respect the per-browser entrypoint option with %j',
async ({ browser, expected, outDir }) => {
const project = new TestProject();
project.addFile(
'entrypoints/background.ts',
`export default defineBackground({
persistent: {
firefox: true,
safari: false,
},
main: () => {},
})`,
);
await project.build({ browser });
const safariManifest = await project.getOutputManifest(
`.output/${outDir}/manifest.json`,
);
expect(safariManifest.background.persistent).toBe(expected);
},
);
});
+86 -14
View File
@@ -43,30 +43,33 @@ describe('Output Directory Structure', () => {
await project.build();
expect(await project.serializeOutput()).toMatchInlineSnapshot(`
".output/chrome-mv3/assets/one.css
expect(
await project.serializeOutput([
'.output/chrome-mv3/content-scripts/one.js',
'.output/chrome-mv3/content-scripts/two.js',
]),
).toMatchInlineSnapshot(`
".output/chrome-mv3/content-scripts/one.css
----------------------------------------
body{color:#00f}
================================================================================
.output/chrome-mv3/assets/two.css
.output/chrome-mv3/content-scripts/one.js
----------------------------------------
<contents-ignored>
================================================================================
.output/chrome-mv3/content-scripts/two.css
----------------------------------------
body{color:red}
================================================================================
.output/chrome-mv3/content-scripts/one.js
----------------------------------------
(function(){\\"use strict\\";function i(n){return n}const s=\\"\\",o={matches:[\\"*://*/*\\"],main:()=>{}};function t(n,...e){if(typeof e[0]==\\"string\\"){const c=e.shift();n(\`[wxt] \${c}\`,...e)}else n(\\"[wxt]\\",...e)}var r={debug:(...n)=>t(console.debug,...n),log:(...n)=>t(console.log,...n),warn:(...n)=>t(console.warn,...n),error:(...n)=>t(console.error,...n)};(async()=>{try{await o.main()}catch(n){r.error(\\"The content script crashed on startup!\\",n)}})()})();
================================================================================
.output/chrome-mv3/content-scripts/two.js
----------------------------------------
(function(){\\"use strict\\";function i(n){return n}const s=\\"\\",o={matches:[\\"*://*/*\\"],main:()=>{}};function t(n,...e){if(typeof e[0]==\\"string\\"){const c=e.shift();n(\`[wxt] \${c}\`,...e)}else n(\\"[wxt]\\",...e)}var r={debug:(...n)=>t(console.debug,...n),log:(...n)=>t(console.log,...n),warn:(...n)=>t(console.warn,...n),error:(...n)=>t(console.error,...n)};(async()=>{try{await o.main()}catch(n){r.error(\\"The content script crashed on startup!\\",n)}})()})();
<contents-ignored>
================================================================================
.output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"content_scripts\\":[{\\"matches\\":[\\"*://*/*\\"],\\"css\\":[\\"assets/one.css\\",\\"assets/two.css\\"],\\"js\\":[\\"content-scripts/one.js\\",\\"content-scripts/two.js\\"]}]}"
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"content_scripts\\":[{\\"matches\\":[\\"*://*/*\\"],\\"css\\":[\\"content-scripts/one.css\\",\\"content-scripts/two.css\\"],\\"js\\":[\\"content-scripts/one.js\\",\\"content-scripts/two.js\\"]}]}"
`);
});
@@ -82,11 +85,14 @@ describe('Output Directory Structure', () => {
await project.build();
expect(await project.serializeOutput()).toMatchInlineSnapshot(`
expect(
await project.serializeOutput([
'.output/chrome-mv3/content-scripts/overlay-one.js',
]),
).toMatchInlineSnapshot(`
".output/chrome-mv3/content-scripts/overlay-one.js
----------------------------------------
(function(){\\"use strict\\";function i(n){return n}const o={matches:[\\"*://*/*\\"],main:()=>{}};function t(n,...e){if(typeof e[0]==\\"string\\"){const c=e.shift();n(\`[wxt] \${c}\`,...e)}else n(\\"[wxt]\\",...e)}var r={debug:(...n)=>t(console.debug,...n),log:(...n)=>t(console.log,...n),warn:(...n)=>t(console.warn,...n),error:(...n)=>t(console.error,...n)};(async()=>{try{await o.main()}catch(n){r.error(\\"The content script crashed on startup!\\",n)}})()})();
<contents-ignored>
================================================================================
.output/chrome-mv3/manifest.json
----------------------------------------
@@ -133,4 +139,70 @@ describe('Output Directory Structure', () => {
false,
);
});
it('should generate a stats file when analyzing the bundle', async () => {
const project = new TestProject();
project.setConfigFileConfig({
analysis: {
enabled: true,
template: 'sunburst',
},
});
project.addFile(
'entrypoints/background.ts',
`export default defineBackground(() => {});`,
);
project.addFile('entrypoints/popup.html', '<html></html>');
project.addFile(
'entrypoints/overlay.content.html',
`export default defineContentScript({
matches: [],
main() {},
});`,
);
await project.build();
expect(await project.fileExists('stats.html')).toBe(true);
});
it('should support JavaScript entrypoints', async () => {
const project = new TestProject();
project.addFile(
'entrypoints/background.js',
`export default defineBackground(() => {});`,
);
project.addFile('entrypoints/unlisted.js', ``);
project.addFile(
'entrypoints/content.js',
`export default defineContentScript({
matches: ["*://*.google.com/*"],
main() {},
})`,
);
project.addFile(
'entrypoints/named.content.jsx',
`export default defineContentScript({
matches: ["*://*.duckduckgo.com/*"],
main() {},
})`,
);
await project.build();
expect(await project.serializeFile('.output/chrome-mv3/manifest.json'))
.toMatchInlineSnapshot(`
".output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"background\\":{\\"service_worker\\":\\"background.js\\"},\\"content_scripts\\":[{\\"matches\\":[\\"*://*.google.com/*\\"],\\"js\\":[\\"content-scripts/content.js\\"]},{\\"matches\\":[\\"*://*.duckduckgo.com/*\\"],\\"js\\":[\\"content-scripts/named.js\\"]}]}"
`);
expect(await project.fileExists('.output/chrome-mv3/background.js'));
expect(
await project.fileExists('.output/chrome-mv3/content-scripts/content.js'),
);
expect(
await project.fileExists('.output/chrome-mv3/content-scripts/named.js'),
);
expect(await project.fileExists('.output/chrome-mv3/unlisted.js'));
});
});
+43
View File
@@ -0,0 +1,43 @@
import { describe, expect, it } from 'vitest';
import { TestProject } from '../utils';
describe('React', () => {
it('should prepare and build an project with a tsx entrypoint', async () => {
const project = new TestProject({
dependencies: {
react: '^18.2.0',
'react-dom': '^18.2.0',
},
devDependencies: {
'@types/react': '^18.2.14',
'@types/react-dom': '^18.2.6',
},
});
project.addFile(
'entrypoints/demo.content.tsx',
`import ReactDOM from 'react-dom/client';
export default defineContentScript({
matches: "<all_urls>",
main() {
const container = document.createElement("div");
document.body.append(container)
const root = ReactDOM.createRoot(container);
root.render(<h1>Hello, world!</h1>);
}
})`,
);
await project.build();
expect(
await project.fileExists('.output/chrome-mv3/content-scripts/demo.js'),
).toBe(true);
expect(await project.serializeFile('.output/chrome-mv3/manifest.json'))
.toMatchInlineSnapshot(`
".output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"description\\":\\"Example description\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"content_scripts\\":[{\\"matches\\":\\"<all_urls>\\",\\"js\\":[\\"content-scripts/demo.js\\"]}]}"
`);
});
});
+11 -10
View File
@@ -22,6 +22,7 @@ describe('TypeScript Project', () => {
const __IS_EDGE__: boolean;
const __IS_OPERA__: boolean;
const __COMMAND__: \\"build\\" | \\"serve\\";
const __ENTRYPOINT__: string;
}
"
`);
@@ -254,14 +255,14 @@ describe('TypeScript Project', () => {
\\"lib\\": [\\"DOM\\", \\"WebWorker\\"],
\\"skipLibCheck\\": true,
\\"paths\\": {
\\"@@\\": [\\"..\\"],
\\"@@/*\\": [\\"../*\\"],
\\"~~\\": [\\"..\\"],
\\"~~/*\\": [\\"../*\\"],
\\"@\\": [\\"..\\"],
\\"@/*\\": [\\"../*\\"],
\\"~\\": [\\"..\\"],
\\"~/*\\": [\\"../*\\"]
\\"~/*\\": [\\"../*\\"],
\\"@@\\": [\\"..\\"],
\\"@@/*\\": [\\"../*\\"],
\\"~~\\": [\\"..\\"],
\\"~~/*\\": [\\"../*\\"]
}
},
\\"include\\": [
@@ -298,14 +299,14 @@ describe('TypeScript Project', () => {
\\"lib\\": [\\"DOM\\", \\"WebWorker\\"],
\\"skipLibCheck\\": true,
\\"paths\\": {
\\"@@\\": [\\"..\\"],
\\"@@/*\\": [\\"../*\\"],
\\"~~\\": [\\"..\\"],
\\"~~/*\\": [\\"../*\\"],
\\"@\\": [\\"../src\\"],
\\"@/*\\": [\\"../src/*\\"],
\\"~\\": [\\"../src\\"],
\\"~/*\\": [\\"../src/*\\"]
\\"~/*\\": [\\"../src/*\\"],
\\"@@\\": [\\"..\\"],
\\"@@/*\\": [\\"../*\\"],
\\"~~\\": [\\"..\\"],
\\"~~/*\\": [\\"../*\\"]
}
},
\\"include\\": [
File diff suppressed because one or more lines are too long
+38 -17
View File
@@ -1,32 +1,36 @@
import { dirname, join, relative, resolve } from 'path';
import fs from 'fs-extra';
import glob from 'fast-glob';
import { execSync } from 'child_process';
import { execaCommand } from 'execa';
import { InlineConfig, UserConfig, build } from '../src';
import { normalizePath } from '../src/core/utils/paths';
import merge from 'lodash.merge';
export class TestProject {
files: Array<[string, string]> = [];
config: UserConfig | undefined;
readonly root: string;
constructor(root = 'e2e/dist') {
constructor(packageJson: any = {}) {
// We can't put each test's project inside e2e/dist directly, otherwise the wxt.config.ts
// file is cached and cannot be different between each test. Instead, we add a random ID to the
// end to make each test's path unique.
const id = Math.random().toString(32).substring(3);
this.root = join(root, id);
this.root = join('e2e/dist', id);
this.files.push([
'package.json',
JSON.stringify(
{
name: 'E2E Extension',
description: 'Example description',
version: '0.0.0-test',
dependencies: {
wxt: '../../..',
merge(
{
name: 'E2E Extension',
description: 'Example description',
version: '0.0.0-test',
dependencies: {
wxt: '../../..',
},
},
},
packageJson,
),
null,
2,
),
@@ -72,17 +76,20 @@ export class TestProject {
await fs.ensureDir(fileDir);
await fs.writeFile(filePath, content ?? '', 'utf-8');
}
execSync('npm i --ignore-scripts', { cwd: this.root });
await execaCommand('npm i --ignore-scripts', { cwd: this.root });
await build({ ...config, root: this.root });
}
/**
* Read all the files from the test project's `.output` directory and combine them into a string
* that can be used in a snapshot.
*
* Optionally, provide a list of filenames whose content is not printed (because it's inconsistent
* or not relevant to a test).
*/
serializeOutput(): Promise<string> {
return this.serializeDir('.output');
serializeOutput(ignoreContentsOfFilenames?: string[]): Promise<string> {
return this.serializeDir('.output', ignoreContentsOfFilenames);
}
/**
@@ -95,7 +102,16 @@ export class TestProject {
);
}
private async serializeDir(dir: string): Promise<string> {
/**
* Deeply print the filename and contents of all files in a directory.
*
* Optionally, provide a list of filenames whose content is not printed (because it's inconsistent
* or not relevant to a test).
*/
private async serializeDir(
dir: string,
ignoreContentsOfFilenames?: string[],
): Promise<string> {
const outputFiles = await glob('**/*', {
cwd: resolve(this.root, dir),
ignore: ['**/node_modules', '**/.output'],
@@ -104,19 +120,24 @@ export class TestProject {
const fileContents = [];
for (const file of outputFiles) {
const path = resolve(this.root, dir, file);
fileContents.push(await this.serializeFile(path));
const isContentIgnored = !!ignoreContentsOfFilenames?.find(
(ignoredFile) => normalizePath(path).endsWith(ignoredFile),
);
fileContents.push(await this.serializeFile(path, isContentIgnored));
}
return fileContents.join(`\n${''.padEnd(80, '=')}\n`);
}
/**
* @param path An abosolute path to a file or a path relative to the root.
* @param ignoreContents An optional boolean that, when true, causes this function to not print
* the file contents.
*/
async serializeFile(path: string): Promise<string> {
async serializeFile(path: string, ignoreContents?: boolean): Promise<string> {
const absolutePath = resolve(this.root, path);
return [
normalizePath(relative(this.root, absolutePath)),
await fs.readFile(absolutePath),
ignoreContents ? '<contents-ignored>' : await fs.readFile(absolutePath),
].join(`\n${''.padEnd(40, '-')}\n`);
}
+19 -8
View File
@@ -1,7 +1,7 @@
{
"name": "wxt",
"type": "module",
"version": "0.5.4",
"version": "0.7.4",
"description": "Next gen framework for developing web extensions",
"engines": {
"node": ">=18.16.0",
@@ -56,33 +56,39 @@
"format:check": "prettier --write .",
"compile": "tsc --noEmit",
"test": "vitest",
"test:coverage": "vitest run --coverage",
"test:coverage": "vitest run --coverage.enabled --coverage.exclude=e2e --coverage.exclude=src/testing",
"prepare": "simple-git-hooks",
"prepublish": "pnpm -s build",
"docs:dev": "vitepress dev docs",
"docs:build": "vitepress build docs",
"docs:preview": "vitepress preview docs",
"sync-releases": "pnpx changelogen@latest gh release all"
"sync-releases": "pnpx changelogen@latest gh release"
},
"dependencies": {
"@types/webextension-polyfill": "^0.10.1",
"@webext-core/fake-browser": "^1.2.2",
"@webext-core/match-patterns": "^1.0.1",
"@webext-core/isolated-element": "^1.0.4",
"@webext-core/match-patterns": "^1.0.2",
"async-mutex": "^0.4.0",
"c12": "^1.4.2",
"cac": "^6.7.14",
"consola": "^3.2.3",
"esbuild": "^0.19.4",
"fast-glob": "^3.3.1",
"filesize": "^10.0.8",
"fs-extra": "^11.1.1",
"get-port": "^7.0.0",
"giget": "^1.1.2",
"immer": "^10.0.2",
"is-wsl": "^3.0.0",
"jiti": "^1.19.1",
"json5": "^2.2.3",
"linkedom": "^0.15.1",
"minimatch": "^9.0.3",
"ora": "^7.0.1",
"picocolors": "^1.0.0",
"prompts": "^2.4.2",
"rollup-plugin-visualizer": "^5.9.2",
"unimport": "^3.1.0",
"vite": "^4.4.7",
"web-ext-run": "^0.1.0",
@@ -94,23 +100,23 @@
"@types/fs-extra": "^11.0.1",
"@types/lodash.merge": "^4.6.7",
"@types/node": "^20.4.5",
"@types/prettier": "^3.0.0",
"@types/prompts": "^2.4.4",
"@vitest/coverage-v8": "^0.34.1",
"execa": "^7.2.0",
"jsdom": "^22.1.0",
"lint-staged": "^14.0.0",
"lodash.merge": "^4.6.2",
"npm-run-all": "^4.1.5",
"ora": "^7.0.1",
"prettier": "^3.0.1",
"simple-git-hooks": "^2.9.0",
"ts-morph": "^19.0.0",
"ts-morph": "^20.0.0",
"tsup": "^7.1.0",
"tsx": "^3.12.7",
"typescript": "^5.1.6",
"typescript": "^5.2.2",
"vitepress": "1.0.0-rc.10",
"vitest": "^0.34.1",
"vitest-mock-extended": "^1.1.4",
"vue": "^3.3.4",
"webextension-polyfill": "^0.10.0"
},
"peerDependencies": {
@@ -123,6 +129,11 @@
"lint-staged": {
"*": "prettier --write"
},
"changelog": {
"excludeAuthors": [
"aaronklinker1@gmail.com"
]
},
"pnpm": {
"peerDependencyRules": {
"ignoreMissing": [
+653 -201
View File
File diff suppressed because it is too large Load Diff
+4
View File
@@ -11,6 +11,7 @@ export const build = defineCommand<
mv3?: boolean;
mv2?: boolean;
debug?: boolean;
analyze?: boolean;
},
]
>(async (root, flags) => {
@@ -21,6 +22,9 @@ export const build = defineCommand<
manifestVersion: flags.mv3 ? 3 : flags.mv2 ? 2 : undefined,
configFile: flags.config,
debug: flags.debug,
analysis: {
enabled: flags.analyze,
},
};
await wxt.build(cliConfig);
+1 -1
View File
@@ -1,6 +1,5 @@
import { defineCommand } from '../utils/defineCommand';
import prompts from 'prompts';
import ora from 'ora';
import { consola } from 'consola';
import { downloadTemplate } from 'giget';
import fs from 'fs-extra';
@@ -133,6 +132,7 @@ async function cloneProject({
template: Template;
packageManager: string;
}) {
const { default: ora } = await import('ora');
const spinner = ora('Downloading template').start();
try {
// 1. Clone repo
+1
View File
@@ -26,6 +26,7 @@ cli
.option('-b, --browser <browser>', 'specify a browser')
.option('--mv3', 'target manifest v3')
.option('--mv2', 'target manifest v2')
.option('--analyze', 'visualize extension bundle')
.action(commands.build);
// ZIP
@@ -0,0 +1,336 @@
/** @vitest-environment jsdom */
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { ContentScriptContext, createContentScriptUi } from '..';
import { createIsolatedElement } from '@webext-core/isolated-element';
import { mock } from 'vitest-mock-extended';
import { browser } from '../browser';
vi.mock('webextension-polyfill', () =>
vi.importActual('../virtual-modules/fake-browser'),
);
vi.mock('@webext-core/isolated-element', async () => {
const { vi } = await import('vitest');
return {
createIsolatedElement: vi.fn(),
};
});
const createIsolatedElementMock = vi.mocked(createIsolatedElement);
const testApp = (container: Element) => {
const app = document.createElement('div');
app.textContent = 'App';
container.append(app);
};
const createCtx = () => new ContentScriptContext('test');
const fetch = vi.fn();
describe('createContentScriptUi', () => {
beforeEach(() => {
document.body.innerHTML = `
<div id="parent">
<p id="one">one</p>
<p id="two">two</p>
<p id="three"></p>
</div>
`;
window.fetch = fetch;
fetch.mockResolvedValue({ text: () => Promise.resolve('') });
createIsolatedElementMock.mockImplementation(async (config) => {
const parentElement = document.createElement(config.name);
const isolatedElement = document.createElement('html');
parentElement.append(isolatedElement);
return {
isolatedElement,
parentElement: parentElement,
shadow: mock<ShadowRoot>({
querySelector: (selector: string) => {
if (selector === 'html') return isolatedElement;
},
}),
};
});
});
describe('css', () => {
it('should load the CSS for the current entrypoint when cssInjectionMode=ui', async () => {
fetch.mockResolvedValue({ text: () => Promise.resolve('body {}') });
const ctx = new ContentScriptContext('test', {
matches: [],
cssInjectionMode: 'ui',
});
await createContentScriptUi(ctx, {
name: 'test',
type: 'inline',
mount: testApp,
});
expect(fetch).toBeCalledTimes(1);
expect(fetch).toBeCalledWith(
`chrome-extension://${browser.runtime.id}/content-scripts/${__ENTRYPOINT__}.css`,
);
expect(createIsolatedElementMock).toBeCalledTimes(1);
expect(createIsolatedElementMock).toBeCalledWith(
expect.objectContaining({
css: {
textContent: 'body {}',
},
}),
);
});
it('should still load the UI when fetch fails to load CSS file when cssInjectionMode=ui', async () => {
const error = Error('Test fetch error');
fetch.mockRejectedValue(error);
const ctx = new ContentScriptContext('test', {
matches: [],
cssInjectionMode: 'ui',
});
await createContentScriptUi(ctx, {
name: 'test',
type: 'inline',
mount: testApp,
});
expect(fetch).toBeCalledTimes(1);
expect(fetch).toBeCalledWith(
`chrome-extension://${browser.runtime.id}/content-scripts/${__ENTRYPOINT__}.css`,
);
expect(createIsolatedElementMock).toBeCalledTimes(1);
expect(createIsolatedElementMock).toBeCalledWith(
expect.objectContaining({
css: {
textContent: '',
},
}),
);
});
it.each(['manifest', 'manual'] as const)(
'should not fetch CSS when cssInjectionMode=%s',
async (cssInjectionMode) => {
const ctx = new ContentScriptContext('test', {
matches: [],
cssInjectionMode,
});
await createContentScriptUi(ctx, {
name: 'test',
type: 'inline',
mount: testApp,
});
expect(fetch).not.toBeCalled();
},
);
});
describe('mount', () => {
describe('append option', () => {
it.each([undefined, 'last' as const])(
'should append the element as the last child to the anchor when append=%s',
async (append) => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test-app',
type: 'inline',
anchor: '#parent',
append,
mount: testApp,
});
ui.mount();
expect(
document.querySelector('#parent > :nth-child(4)')?.tagName,
).toEqual('TEST-APP');
},
);
it('should append the element as the first child to the anchor when append=first', async () => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test-app',
type: 'inline',
anchor: '#parent',
append: 'first',
mount: testApp,
});
ui.mount();
expect(
document.querySelector('#parent > :nth-child(1)')?.tagName,
).toEqual('TEST-APP');
});
it('should append the element normally when append=first but there are no other children', async () => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test-app',
type: 'inline',
anchor: '#three',
append: 'first',
mount: testApp,
});
ui.mount();
expect(
document.querySelector('#three > :nth-child(1)')?.tagName,
).toEqual('TEST-APP');
});
it('should replace the anchor with the element when append=replace', async () => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test-app',
type: 'inline',
anchor: '#two',
append: 'replace',
mount: testApp,
});
ui.mount();
expect(
document.querySelector('#parent > :nth-child(2)')?.tagName,
).toEqual('TEST-APP');
});
it('should append the element after the anchor when append=before', async () => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test-app',
type: 'inline',
anchor: '#two',
append: 'before',
mount: testApp,
});
ui.mount();
expect(
document.querySelector('#parent > :nth-child(2)')?.tagName,
).toEqual('TEST-APP');
});
it('should append the element after the anchor when append=after', async () => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test-app',
type: 'inline',
anchor: '#two',
append: 'after',
mount: testApp,
});
ui.mount();
expect(
document.querySelector('#parent > :nth-child(3)')?.tagName,
).toEqual('TEST-APP');
});
it('should apply a custom function', async () => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test-app',
type: 'inline',
anchor: '#three',
append: (anchor, ui) => anchor.replaceWith(ui),
mount: testApp,
});
ui.mount();
expect(
document.querySelector('#parent > :nth-child(3)')?.tagName,
).toEqual('TEST-APP');
});
});
it('should default the anchor to the body when unset', async () => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test-app',
type: 'inline',
mount: testApp,
});
ui.mount();
expect(document.querySelector('body > :nth-child(2)')?.tagName).toEqual(
'TEST-APP',
);
});
it.each(['#four', () => document.querySelector('#four')])(
"should throw an error if the anchor doesn't exist",
async (anchor) => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test',
type: 'inline',
anchor,
mount: testApp,
});
expect(ui.mount).toThrow(
'Failed to mount content script ui: could not find anchor element',
);
},
);
});
describe('remove', () => {
it("should not fail if the ui hasn't been mounted", async () => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test-app',
type: 'inline',
mount: testApp,
});
ui.remove();
});
it('should automatically remove the UI when the context is invalidated', async () => {
const ctx = createCtx();
const ui = await createContentScriptUi(ctx, {
name: 'test-app',
type: 'inline',
mount: testApp,
});
ui.mount();
expect(document.querySelector('test-app')).toBeDefined();
ctx.abort();
expect(document.querySelector('test-app')).toBeNull();
});
});
describe('type', () => {
it.each(['inline', 'overlay', 'modal'] as const)(
'should render type=%s',
async (type) => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test-app',
type,
mount: testApp,
});
ui.mount();
expect(document.querySelector('test-app')).toBeDefined();
},
);
});
describe('anchor', () => {
it.each([
() => '#two',
() => () => '#two',
() => document.querySelector('#two'),
() => () => document.querySelector('#two'),
])('should render anchor=%s', async (getAnchor) => {
const ui = await createContentScriptUi(createCtx(), {
name: 'test-app',
type: 'inline',
anchor: getAnchor(),
mount: testApp,
});
ui.mount();
expect(document.querySelector('test-app')).toBeDefined();
});
});
});
+298
View File
@@ -0,0 +1,298 @@
import { createIsolatedElement } from '@webext-core/isolated-element';
import { browser } from './browser';
import { logger } from './utils/logger';
import { ContentScriptContext } from '.';
/**
* Utility for mounting content script UI's with isolated styles. Automatically removed from the DOM
* when the content script's context is invalidated.
*
* See <https://wxt.dev/entrypoints/content-scripts.html#ui> for full documentation.
*
* @example
* // entrypoints/example-ui.content/index.ts
* import "./style.css"
*
* export default defineContentScript({
* matches: ["*://*.google.com/*"],
* cssInjectionMode: "ui",
*
* async main(ctx) {
* const ui = await createContentScriptUi(ctx, {
* name: "example-overlay",
* type: "modal",
* mount(container) {
* const app = document.createElement("div");
* app.textContent = "Content Script UI";
* container.append(app);
* }
* })
* ui.mount();
* }
* })
*/
export async function createContentScriptUi<T>(
ctx: ContentScriptContext,
options: ContentScriptUiOptions<T>,
): Promise<ContentScriptUi<T>> {
const css = [options.css ?? ''];
if (ctx.options?.cssInjectionMode === 'ui') {
css.push(await loadCss());
}
const {
isolatedElement: uiContainer,
parentElement: shadowHost,
shadow,
} = await createIsolatedElement({
name: options.name,
css: {
textContent: css.join('\n').trim(),
},
mode: 'open',
});
const getAnchor = (): Element | undefined => {
if (options.anchor == null) return document.body;
let resolved =
typeof options.anchor === 'function' ? options.anchor() : options.anchor;
if (typeof resolved === 'string')
return document.querySelector<Element>(resolved) ?? undefined;
return resolved ?? undefined;
};
let mounted: T;
const mount = () => {
const anchor = getAnchor();
if (anchor == null)
throw Error(
'Failed to mount content script ui: could not find anchor element',
);
// Mount UI inside shadow root
mounted = options.mount(uiContainer);
// Add shadow root element to DOM
switch (options.append) {
case undefined:
case 'last':
anchor.append(shadowHost);
break;
case 'first':
if (anchor.firstChild) {
anchor.insertBefore(shadowHost, anchor.firstChild);
} else {
anchor.append(shadowHost);
}
break;
case 'replace':
anchor.replaceWith(shadowHost);
break;
case 'after':
anchor.replaceWith(anchor, shadowHost);
break;
case 'before':
anchor.replaceWith(shadowHost, anchor);
break;
default:
options.append(anchor, shadowHost);
break;
}
// Apply types
if (options.type !== 'inline') {
if (options.zIndex != null)
shadowHost.style.zIndex = String(options.zIndex);
shadowHost.style.overflow = 'visible';
shadowHost.style.position = 'relative';
shadowHost.style.width = '0';
shadowHost.style.height = '0';
shadowHost.style.display = 'block';
const html = shadow.querySelector('html')!;
// HTML doesn't exist in tests
if (options.type === 'overlay') {
html.style.position = 'absolute';
if (options.alignment?.startsWith('bottom-')) html.style.bottom = '0';
else html.style.top = '0';
if (options.alignment?.endsWith('-right')) html.style.right = '0';
else html.style.left = '0';
} else {
html.style.position = 'fixed';
html.style.top = '0';
html.style.bottom = '0';
html.style.left = '0';
html.style.right = '0';
}
}
};
const remove = () => {
// Detatch shadow root from DOM
shadowHost.remove();
// Cleanup mounted state
options.onRemove?.(mounted);
// Remove children from uiContainer
while (uiContainer.lastChild)
uiContainer.removeChild(uiContainer.lastChild);
};
ctx.onInvalidated(remove);
return {
shadow,
shadowHost,
uiContainer,
mount,
remove,
mounted: mounted!,
};
}
/**
* Load the CSS for the current entrypoint.
*/
async function loadCss(): Promise<string> {
const url = browser.runtime.getURL(`/content-scripts/${__ENTRYPOINT__}.css`);
try {
const res = await fetch(url);
const css = await res.text();
// Replace :root selectors with :host since we're in a shadow root
return css.replaceAll(':root', ':host');
} catch (err) {
logger.warn(
`Failed to load styles @ ${url}. Did you forget to import the stylesheet in your entrypoint?`,
err,
);
return '';
}
}
export interface ContentScriptUi<T> {
/**
* The `HTMLElement` hosting the shadow root used to isolate the UI's styles. This is the element
* that get's added to the DOM. This element's style is not isolated from the webpage.
*/
shadowHost: HTMLElement;
/**
* The container element inside the `ShadowRoot` whose styles are isolated. The UI is mounted
* inside this `HTMLElement`.
*/
uiContainer: HTMLElement;
/**
* The shadow root performing the isolation.
*/
shadow: ShadowRoot;
/**
* Custom data returned from the `options.mount` function.
*/
mounted: T;
/**
* Function that mounts or remounts the UI on the page.
*/
mount: () => void;
/**
* Function that removes the UI from the webpage.
*/
remove: () => void;
}
interface BaseContentScriptUiOptions<T> {
/**
* The name of the custom component used to host the ShadowRoot. Must be kebab-case.
*/
name: string;
/**
* In combination with `anchor`, decide how to add the UI to the DOM.
*
* - `"last"` (default) - Add the UI as the last child of the `anchor` element
* - `"first"` - Add the UI as the last child of the `anchor` element
* - `"replace"` - Replace the `anchor` element with the UI.
* - `"before"` - Add the UI as the sibling before the `anchor` element
* - `"after"` - Add the UI as the sibling after the `anchor` element
* - `(anchor, ui) => void` - Customizable function that let's you add the UI to the DOM
*/
append?: ContentScriptAppendMode | ((anchor: Element, ui: Element) => void);
/**
* A CSS selector, element, or function that returns one of the two. Along with `append`, the
* `anchor` dictates where in the page the UI will be added.
*/
anchor?:
| string
| Element
| null
| undefined
| (() => string | Element | null | undefined);
/**
* Callback executed when mounting the UI. This function should create and append the UI to the
* `container` element. It is called every time `ui.mount()` is called
*
* Optionally return a value that can be accessed at `ui.mounted` or in the `onRemove` callback.
*/
mount: (container: Element) => T;
/**
* Callback called when the UI is removed from the webpage. Use to cleanup your UI, like
* unmounting your vue or react apps.
*/
onRemove?: (mounted: T) => void;
/**
* Custom CSS text to apply to the UI. If your content script imports/generates CSS and you've
* set `cssInjectionMode: "ui"`, the imported CSS will be included automatically. You do not need
* to pass those styles in here. This is for any additional styles not in the imported CSS.
*
* See <https://wxt.dev/entrypoints/content-scripts.html#ui> for more info.
*/
css?: string;
}
export type OverlayContentScriptUiOptions<T> = BaseContentScriptUiOptions<T> & {
type: 'overlay';
/**
* When using `type: "overlay"`, the mounted element is 0px by 0px in size. Alignment specifies
* which corner is aligned with that 0x0 pixel space.
*
* @default "top-left"
*/
alignment?: ContentScriptUiOverlayAlignment;
/**
* The `z-index` used on the `shadowHost`. Set to a positive number to show your UI over website
* content.
*/
zIndex?: number;
};
export type ModalContentScriptUiOptions<T> = BaseContentScriptUiOptions<T> & {
type: 'modal';
/**
* The `z-index` used on the `shadowHost`. Set to a positive number to show your UI over website
* content.
*/
zIndex?: number;
};
export type InlineContentScriptUiOptions<T> = BaseContentScriptUiOptions<T> & {
type: 'inline';
};
export type ContentScriptUiOverlayAlignment =
| 'top-left'
| 'top-right'
| 'bottom-left'
| 'bottom-right';
export type ContentScriptAppendMode =
| 'last'
| 'first'
| 'replace'
| 'before'
| 'after';
export type ContentScriptUiOptions<T> =
| OverlayContentScriptUiOptions<T>
| ModalContentScriptUiOptions<T>
| InlineContentScriptUiOptions<T>;
+2 -1
View File
@@ -1,3 +1,4 @@
export * from './defineContentScript';
export * from './defineBackground';
export * from './mountContentScriptUi';
export * from './createContentScriptUi';
export * from './utils/ContentScriptContext';
-3
View File
@@ -1,3 +0,0 @@
export function mountContentScriptUi() {
throw Error('Not implemented: mountContentScriptUi');
}
+186
View File
@@ -0,0 +1,186 @@
import { ContentScriptDefinition } from '../../core/types';
import { browser } from '../browser';
import { logger } from './logger';
/**
* Extends [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).
* Used to detect and stop content script code when the script is invalidated.
*
* It also provides several utilities like `ctx.setTimeout` and `ctx.setInterval` that should be used in
* content scripts instead of `window.setTimeout` or `window.setInterval`.
*/
export class ContentScriptContext extends AbortController {
static SCRIPT_STARTED_MESSAGE_TYPE = 'wxt:content-script-started';
#isTopFrame = window.self === window.top;
constructor(
private readonly contentScriptName: string,
public readonly options?: Omit<ContentScriptDefinition, 'main'>,
) {
super();
if (this.#isTopFrame) {
this.#stopOldScripts();
}
this.setTimeout(() => {
// Run on next tick so the listener it adds isn't triggered by stopOldScript
this.#listenForNewerScripts();
});
}
get isInvalid(): boolean {
if (browser.runtime.id == null) {
this.notifyInvalidated(); // Sets `signal.aborted` to true
}
return this.signal.aborted;
}
get isValid(): boolean {
return !this.isInvalid;
}
/**
* Add a listener that is called when the content script's context is invalidated.
*
* @returns A function to remove the listener.
*
* @example
* browser.runtime.onMessage.addListener(cb);
* const removeInvalidatedListener = ctx.onInvalidated(() => {
* browser.runtime.onMessage.removeListener(cb);
* })
* // ...
* removeInvalidatedListener();
*/
onInvalidated(cb: () => void): () => void {
this.signal.addEventListener('abort', cb);
return () => this.signal.removeEventListener('abort', cb);
}
/**
* Return a promise that never resolves. Useful if you have an async function that shouldn't run
* after the context is expired.
*
* @example
* const getValueFromStorage = async () => {
* if (ctx.isInvalid) return ctx.block();
*
* // ...
* }
*/
block<T>(): Promise<T> {
return new Promise(() => {
// noop
});
}
/**
* Wrapper around `window.setInterval` that automatically clears the interval when invalidated.
*/
setInterval(handler: () => void, timeout?: number): number {
const id = setInterval(() => {
if (this.isValid) handler();
}, timeout) as unknown as number;
this.onInvalidated(() => clearInterval(id));
return id;
}
/**
* Wrapper around `window.setTimeout` that automatically clears the interval when invalidated.
*/
setTimeout(handler: () => void, timeout?: number): number {
const id = setTimeout(() => {
if (this.isValid) handler();
}, timeout) as unknown as number;
this.onInvalidated(() => clearTimeout(id));
return id;
}
/**
* Wrapper around `window.requestAnimationFrame` that automatically cancels the request when
* invalidated.
*/
requestAnimationFrame(callback: FrameRequestCallback): number {
const id = requestAnimationFrame((...args) => {
if (this.isValid) callback(...args);
});
this.onInvalidated(() => cancelAnimationFrame(id));
return id;
}
/**
* Wrapper around `window.requestIdleCallback` that automatically cancels the request when
* invalidated.
*/
requestIdleCallback(
callback: IdleRequestCallback,
options?: IdleRequestOptions,
): number {
const id = requestIdleCallback((...args) => {
if (!this.signal.aborted) callback(...args);
}, options);
this.onInvalidated(() => cancelIdleCallback(id));
return id;
}
/**
* Call `target.addEventListener` and remove the event listener when the context is invalidated.
*
* @example
* ctx.addEventListener(window, "mousemove", () => {
* // ...
* });
* ctx.addEventListener(document, "visibilitychange", () => {
* // ...
* });
*/
addEventListener(
target: any,
type: string,
handler: (event: Event) => void,
options?: AddEventListenerOptions,
) {
target.addEventListener?.(type, handler, options);
this.onInvalidated(
() => target.removeEventListener?.(type, handler, options),
);
}
/**
* Abort the abort controller and execute all `onInvalidated` listeners.
*/
notifyInvalidated() {
this.abort('Content script context invalidated');
logger.debug(
`Content script "${this.contentScriptName}" context invalidated`,
);
}
#stopOldScripts() {
// Use postMessage so it get's sent to all the frames of the page.
window.postMessage(
{
event: ContentScriptContext.SCRIPT_STARTED_MESSAGE_TYPE,
contentScriptName: this.contentScriptName,
},
'*',
);
}
#listenForNewerScripts() {
const cb = (event: MessageEvent) => {
if (
event.data?.type === ContentScriptContext.SCRIPT_STARTED_MESSAGE_TYPE &&
event.data?.contentScriptName === this.contentScriptName
) {
this.notifyInvalidated();
}
};
addEventListener('message', cb);
this.onInvalidated(() => removeEventListener('message', cb));
}
}
+2
View File
@@ -1,4 +1,6 @@
function print(method: (...args: any[]) => void, ...args: any[]) {
if (import.meta.env.MODE === 'production') return;
if (typeof args[0] === 'string') {
const message = args.shift();
method(`[wxt] ${message}`, ...args);
@@ -1,9 +1,13 @@
import definition from 'virtual:user-content-script';
import { logger } from '../utils/logger';
import { ContentScriptContext } from '../utils/ContentScriptContext';
(async () => {
try {
await definition.main();
const { main, ...options } = definition;
const ctx = new ContentScriptContext(__ENTRYPOINT__, options);
await main(ctx);
} catch (err) {
logger.error('The content script crashed on startup!', err);
}
@@ -21,3 +21,4 @@ declare const __DEV_SERVER_PROTOCOL__: string;
declare const __DEV_SERVER_HOSTNAME__: string;
declare const __DEV_SERVER_PORT__: string;
declare const __MANIFEST_VERSION__: 2 | 3;
declare const __ENTRYPOINT__: string;
+32 -1
View File
@@ -11,6 +11,9 @@ import fs from 'fs-extra';
import { groupEntrypoints } from './utils/groupEntrypoints';
import { formatDuration } from './utils/formatDuration';
import { printBuildSummary } from './log/printBuildSummary';
import { execaCommand } from 'execa';
import glob from 'fast-glob';
import { unnormalizePath } from './utils/paths';
/**
* Builds the extension based on an internal config.
@@ -50,6 +53,13 @@ export async function buildInternal(
config,
);
if (config.analysis.enabled) {
await combineAnalysisStats(config);
config.logger.info(
`Analysis complete:\n ${pc.gray('└─')} ${pc.yellow('stats.html')}`,
);
}
return output;
}
@@ -71,6 +81,9 @@ export async function rebuild(
publicAssets: [],
},
): Promise<{ output: BuildOutput; manifest: Manifest.WebExtensionManifest }> {
const { default: ora } = await import('ora');
const spinner = ora(`Preparing...`).start();
// Update types directory with new files and types
const allEntrypoints = await findEntrypoints(config);
await generateTypesDir(allEntrypoints, config).catch((err) => {
@@ -80,7 +93,7 @@ export async function rebuild(
});
// Build and merge the outputs
const newOutput = await buildEntrypoints(entrypointGroups, config);
const newOutput = await buildEntrypoints(entrypointGroups, config, spinner);
const mergedOutput: Omit<BuildOutput, 'manifest'> = {
steps: [...existingOutput.steps, ...newOutput.steps],
publicAssets: [...existingOutput.publicAssets, ...newOutput.publicAssets],
@@ -99,6 +112,9 @@ export async function rebuild(
// Write manifest
await writeManifest(newManifest, finalOutput, config);
// Stop the spinner and remove it from the CLI output
spinner.clear().stop();
return {
output: {
manifest: newManifest,
@@ -111,3 +127,18 @@ export async function rebuild(
manifest: newManifest,
};
}
async function combineAnalysisStats(config: InternalConfig): Promise<void> {
const unixFiles = await glob(`stats-*.json`, {
cwd: config.outDir,
absolute: true,
});
const absolutePaths = unixFiles.map(unnormalizePath);
await execaCommand(
`rollup-plugin-visualizer ${absolutePaths.join(' ')} --template ${
config.analysis.template
}`,
{ cwd: config.root, stdio: 'inherit' },
);
}
+36 -7
View File
@@ -12,13 +12,26 @@ import { getEntrypointBundlePath } from '../utils/entrypoints';
import fs from 'fs-extra';
import { dirname, resolve } from 'path';
import { getPublicFiles } from '../utils/public';
import { getEntrypointGlobals } from '../utils/globals';
import type { Ora } from 'ora';
import pc from 'picocolors';
export async function buildEntrypoints(
groups: EntrypointGroup[],
config: InternalConfig,
spinner: Ora,
): Promise<Omit<BuildOutput, 'manifest'>> {
const steps: BuildStepOutput[] = [];
for (const group of groups) {
for (let i = 0; i < groups.length; i++) {
const group = groups[i];
spinner.text =
pc.dim(`[${i + 1}/${groups.length}]`) +
` ${[group]
.flat()
.map((e) => e.name)
.join(pc.dim(', '))}`;
const step = Array.isArray(group)
? await buildMultipleEntrypoints(group, config)
: await buildSingleEntrypoint(group, config);
@@ -71,17 +84,29 @@ async function buildSingleEntrypoint(
config.outDir,
'.js',
),
// Output content script CSS to assets/ with a hash to prevent conflicts. Defaults to
// "[name].[ext]" in lib mode, which usually results in "style.css". That means multiple
// content scripts with styles would overwrite each other if it weren't changed below.
assetFileNames: `assets/${entrypoint.name}.[ext]`,
// Output content script CSS to `content-scripts/`, but all other scripts are written to
// `assets/`.
assetFileNames: ({ name }) => {
if (entrypoint.type === 'content-script' && name?.endsWith('css')) {
return `content-scripts/${entrypoint.name}.[ext]`;
} else {
return `assets/${entrypoint.name}.[ext]`;
}
},
},
},
},
define: {
// See https://github.com/aklinker1/vite-plugin-web-extension/issues/96
'process.env.NODE_ENV': JSON.stringify(config.mode),
},
};
for (const global of getEntrypointGlobals(config, entrypoint.name)) {
libMode.define![global.name] = JSON.stringify(global.value);
}
const entryConfig = vite.mergeConfig(
libMode,
config.vite,
await config.vite(config.env),
) as vite.InlineConfig;
const result = await vite.build(entryConfig);
@@ -116,11 +141,15 @@ async function buildMultipleEntrypoints(
},
},
},
define: {},
};
for (const global of getEntrypointGlobals(config, 'html')) {
multiPage.define![global.name] = JSON.stringify(global.value);
}
const entryConfig = vite.mergeConfig(
multiPage,
config.vite,
await config.vite(config.env),
) as vite.UserConfig;
const result = await vite.build(entryConfig);
+16 -9
View File
@@ -17,7 +17,10 @@ import { parseHTML } from 'linkedom';
import JSON5 from 'json5';
import { importEntrypointFile } from '../utils/importEntrypointFile';
import glob from 'fast-glob';
import { getEntrypointName } from '../utils/entrypoints';
import {
getEntrypointName,
resolvePerBrowserOption,
} from '../utils/entrypoints';
import { VIRTUAL_NOOP_BACKGROUND_MODULE_ID } from '../vite-plugins/noopBackground';
import { CSS_EXTENSIONS_PATTERN } from '../utils/paths';
@@ -300,7 +303,11 @@ async function getBackgroundEntrypoint(
name: 'background',
inputPath: path,
outputDir: config.outDir,
options: options,
options: {
...options,
type: resolvePerBrowserOption(options.type, config.browser),
persistent: resolvePerBrowserOption(options.persistent, config.browser),
},
};
}
@@ -349,14 +356,14 @@ const PATH_GLOB_TO_TYPE_MAP: Record<string, Entrypoint['type'] | 'ignored'> = {
'devtools.html': 'devtools',
'devtools/index.html': 'devtools',
'background.ts': 'background',
'background/index.ts': 'background',
'background.[jt]s': 'background',
'background/index.[jt]s': 'background',
[VIRTUAL_NOOP_BACKGROUND_MODULE_ID]: 'background',
'content.ts?(x)': 'content-script',
'content/index.ts?(x)': 'content-script',
'*.content.ts?(x)': 'content-script',
'*.content/index.ts?(x)': 'content-script',
'content.[jt]s?(x)': 'content-script',
'content/index.[jt]s?(x)': 'content-script',
'*.content.[jt]s?(x)': 'content-script',
'*.content/index.[jt]s?(x)': 'content-script',
[`content.${CSS_EXTENSIONS_PATTERN}`]: 'content-script-style',
[`*.content.${CSS_EXTENSIONS_PATTERN}`]: 'content-script-style',
[`content/index.${CSS_EXTENSIONS_PATTERN}`]: 'content-script-style',
@@ -370,7 +377,7 @@ const PATH_GLOB_TO_TYPE_MAP: Record<string, Entrypoint['type'] | 'ignored'> = {
'*.html': 'unlisted-page',
'*/index.html': 'unlisted-page',
'*.ts': 'unlisted-script',
'*.[jt]s': 'unlisted-script',
'*/index.ts': 'unlisted-script',
[`*.${CSS_EXTENSIONS_PATTERN}`]: 'unlisted-style',
[`*/index.${CSS_EXTENSIONS_PATTERN}`]: 'unlisted-style',
+7 -7
View File
@@ -4,7 +4,7 @@ import fs from 'fs-extra';
import { relative, resolve } from 'path';
import { getEntrypointBundlePath } from '../utils/entrypoints';
import { getUnimportOptions } from '../utils/auto-imports';
import { getGlobals } from '../utils/globals';
import { getEntrypointGlobals, getGlobals } from '../utils/globals';
import { getPublicFiles } from '../utils/public';
import { normalizePath } from '../utils/paths';
import path from 'node:path';
@@ -157,7 +157,7 @@ async function writeGlobalsDeclarationFile(
config: InternalConfig,
): Promise<string> {
const filePath = resolve(config.typesDir, 'globals.d.ts');
const globals = getGlobals(config);
const globals = [...getGlobals(config), ...getEntrypointGlobals(config, '')];
await writeFileIfDifferent(
filePath,
[
@@ -213,14 +213,14 @@ async function writeTsConfigFile(
"lib": ["DOM", "WebWorker"],
"skipLibCheck": true,
"paths": {
"@@": ["${rootPath}"],
"@@/*": ["${rootPath}/*"],
"~~": ["${rootPath}"],
"~~/*": ["${rootPath}/*"],
"@": ["${srcPath}"],
"@/*": ["${srcPath}/*"],
"~": ["${srcPath}"],
"~/*": ["${srcPath}/*"]
"~/*": ["${srcPath}/*"],
"@@": ["${rootPath}"],
"@@/*": ["${rootPath}/*"],
"~~": ["${rootPath}"],
"~~/*": ["${rootPath}/*"]
}
},
"include": [
+79
View File
@@ -0,0 +1,79 @@
import { describe, expect, it, vi } from 'vitest';
import { createExtensionRunner } from '..';
import { fakeInternalConfig } from '../../../testing/fake-objects';
import { mock } from 'vitest-mock-extended';
import { createSafariRunner } from '../safari';
import { ExtensionRunner } from '../extension-runner';
import { createWslRunner } from '../wsl';
import { createManualRunner } from '../manual';
import { isWsl } from '../../utils/wsl';
import { createWebExtRunner } from '../web-ext';
vi.mock('../../utils/wsl');
const isWslMock = vi.mocked(isWsl);
vi.mock('../safari');
const createSafariRunnerMock = vi.mocked(createSafariRunner);
vi.mock('../wsl');
const createWslRunnerMock = vi.mocked(createWslRunner);
vi.mock('../manual');
const createManualRunnerMock = vi.mocked(createManualRunner);
vi.mock('../web-ext');
const createWebExtRunnerMock = vi.mocked(createWebExtRunner);
describe('createExtensionRunner', () => {
it('should return a Safari runner when browser is "safari"', async () => {
const config = fakeInternalConfig({
browser: 'safari',
});
const safariRunner = mock<ExtensionRunner>();
createSafariRunnerMock.mockReturnValue(safariRunner);
await expect(createExtensionRunner(config)).resolves.toBe(safariRunner);
});
it('should return a WSL runner when `is-wsl` is true', async () => {
isWslMock.mockResolvedValueOnce(true);
const config = fakeInternalConfig({
browser: 'chrome',
});
const wslRunner = mock<ExtensionRunner>();
createWslRunnerMock.mockReturnValue(wslRunner);
await expect(createExtensionRunner(config)).resolves.toBe(wslRunner);
});
it('should return a manual runner when `runner.disabled` is true', async () => {
isWslMock.mockResolvedValueOnce(false);
const config = fakeInternalConfig({
browser: 'chrome',
runnerConfig: {
config: {
disabled: true,
},
},
});
const manualRunner = mock<ExtensionRunner>();
createManualRunnerMock.mockReturnValue(manualRunner);
await expect(createExtensionRunner(config)).resolves.toBe(manualRunner);
});
it('should return a web-ext runner otherwise', async () => {
const config = fakeInternalConfig({
browser: 'chrome',
runnerConfig: {
config: {
disabled: undefined,
},
},
});
const manualRunner = mock<ExtensionRunner>();
createWebExtRunnerMock.mockReturnValue(manualRunner);
await expect(createExtensionRunner(config)).resolves.toBe(manualRunner);
});
});
+18
View File
@@ -0,0 +1,18 @@
import { InternalConfig } from '../types';
import { ExtensionRunner } from './extension-runner';
import { createWslRunner } from './wsl';
import { createWebExtRunner } from './web-ext';
import { createSafariRunner } from './safari';
import { createManualRunner } from './manual';
import { isWsl } from '../utils/wsl';
export async function createExtensionRunner(
config: InternalConfig,
): Promise<ExtensionRunner> {
if (config.browser === 'safari') return createSafariRunner();
if (await isWsl()) return createWslRunner();
if (config.runnerConfig.config?.disabled) return createManualRunner();
return createWebExtRunner();
}
+21
View File
@@ -0,0 +1,21 @@
import { ExtensionRunner } from './extension-runner';
import { relative } from 'node:path';
/**
* The manual runner tells the user to load the unpacked extension manually.
*/
export function createManualRunner(): ExtensionRunner {
return {
async openBrowser(config) {
config.logger.info(
`Load "${relative(
process.cwd(),
config.outDir,
)}" as an unpacked extension manually`,
);
},
async closeBrowser() {
// noop
},
};
}
+21
View File
@@ -0,0 +1,21 @@
import { ExtensionRunner } from './extension-runner';
import { relative } from 'node:path';
/**
* The Safari runner just logs a warning message because `web-ext` doesn't work with Safari.
*/
export function createSafariRunner(): ExtensionRunner {
return {
async openBrowser(config) {
config.logger.warn(
`Cannot Safari using web-ext. Load "${relative(
process.cwd(),
config.outDir,
)}" as an unpacked extension manually`,
);
},
async closeBrowser() {
// noop
},
};
}
@@ -1,5 +1,5 @@
import type { WebExtRunInstance } from 'web-ext-run';
import { ExtensionRunner } from './ExtensionRunner';
import { ExtensionRunner } from './extension-runner';
/**
* Create an `ExtensionRunner` backed by `web-ext`.
@@ -9,10 +9,7 @@ export function createWebExtRunner(): ExtensionRunner {
return {
async openBrowser(config) {
if (config.browser === 'safari') {
config.logger.warn('Cannot open safari automatically.');
return;
}
config.logger.info('Opening browser...');
// Use the plugin's logger instead of web-ext's built-in one.
const webExtLogger = await import('web-ext-run/util/logger');
@@ -57,6 +54,8 @@ export function createWebExtRunner(): ExtensionRunner {
const webExt = await import('web-ext-run');
runner = await webExt.default.cmd.run(finalConfig, options);
config.logger.success('Opened!');
},
async closeBrowser() {
+21
View File
@@ -0,0 +1,21 @@
import { ExtensionRunner } from './extension-runner';
import { relative } from 'node:path';
/**
* The WSL runner just logs a warning message because `web-ext` doesn't work in WSL.
*/
export function createWslRunner(): ExtensionRunner {
return {
async openBrowser(config) {
config.logger.warn(
`Cannot open browser when using WSL. Load "${relative(
process.cwd(),
config.outDir,
)}" as an unpacked extension manually`,
);
},
async closeBrowser() {
// noop
},
};
}
+25 -9
View File
@@ -6,10 +6,16 @@ import {
} from './types';
import * as vite from 'vite';
import { Scripting } from 'webextension-polyfill';
import { getEntrypointBundlePath } from './utils/entrypoints';
import { getContentScriptCssFiles } from './utils/manifest';
import { createWebExtRunner } from './runners/createWebExtRunner';
import {
getEntrypointBundlePath,
resolvePerBrowserOption,
} from './utils/entrypoints';
import {
getContentScriptCssFiles,
getContentScriptsCssMap,
} from './utils/manifest';
import { buildInternal } from './build';
import { createExtensionRunner } from './runners';
export async function getServerInfo(): Promise<ServerInfo> {
const { default: getPort, portNumbers } = await import('get-port');
@@ -34,10 +40,10 @@ export async function setupServer(
serverInfo: ServerInfo,
config: InternalConfig,
): Promise<WxtDevServer> {
const runner = createWebExtRunner();
const runner = await createExtensionRunner(config);
const viteServer = await vite.createServer(
vite.mergeConfig(serverInfo, config.vite),
vite.mergeConfig(serverInfo, await config.vite(config.env)),
);
const start = async () => {
@@ -45,9 +51,7 @@ export async function setupServer(
config.logger.success(`Started dev server @ ${serverInfo.origin}`);
server.currentOutput = await buildInternal(config);
config.logger.info('Opening browser...');
await runner.openBrowser(config);
config.logger.success('Opened!');
};
const reloadExtension = () => {
@@ -101,10 +105,22 @@ export function reloadContentScripts(
if (Array.isArray(entry) || entry.type !== 'content-script') return;
const js = [getEntrypointBundlePath(entry, config.outDir, '.js')];
const css = getContentScriptCssFiles([entry], server.currentOutput);
const cssMap = getContentScriptsCssMap(server.currentOutput, [entry]);
const css = getContentScriptCssFiles([entry], cssMap);
server.reloadContentScript({
...entry.options,
allFrames: resolvePerBrowserOption(
entry.options.allFrames,
config.browser,
),
excludeMatches: resolvePerBrowserOption(
entry.options.excludeMatches,
config.browser,
),
matches: resolvePerBrowserOption(entry.options.matches, config.browser),
runAt: resolvePerBrowserOption(entry.options.runAt, config.browser),
// @ts-expect-error: Chrome accepts this, not typed in webextension-polyfill (https://developer.chrome.com/docs/extensions/reference/scripting/#type-RegisteredContentScript)
world: resolvePerBrowserOption(entry.options.world, config.browser),
js,
css,
});
+79 -16
View File
@@ -3,6 +3,8 @@ import { Manifest, Scripting } from 'webextension-polyfill';
import { UnimportOptions } from 'unimport';
import { EntrypointGroup } from '.';
import { LogLevel } from 'consola';
import { ContentScriptContext } from '../../client/utils/ContentScriptContext';
import type { PluginVisualizerOptions } from 'rollup-plugin-visualizer';
export interface InlineConfig {
/**
@@ -83,13 +85,16 @@ export interface InlineConfig {
*/
logger?: Logger;
/**
* Custom Vite options, see <https://vitejs.dev/config/shared-options.html>.
* Return custom Vite options from a function. See
* <https://vitejs.dev/config/shared-options.html>.
*
* [`root`](#root), [`configFile`](#configfile), and [`mode`](#mode) should be set in WXT's config.
* [`root`](#root), [`configFile`](#configfile), and [`mode`](#mode) should be set in WXT's config
* instead of Vite's.
*
* This is a function because any vite plugins added need to be recreated for each individual
* build step, incase they have internal state causing them to fail when reused.
*/
vite?:
| WxtViteConfig
| ((env: ConfigEnv) => WxtViteConfig | Promise<WxtViteConfig>);
vite?: (env: ConfigEnv) => WxtViteConfig | Promise<WxtViteConfig>;
/**
* Customize the `manifest.json` output. Can be an object, promise, or function that returns an
* object or promise.
@@ -151,6 +156,41 @@ export interface InlineConfig {
*/
ignoredSources?: string[];
};
/**
* Transform the final manifest before it's written to the file system. Edit the `manifest`
* parameter directly, do not return a new object. Return values are ignored.
*
* @example
* defineConfig({
* // Add a CSS-only content script.
* transformManifest(manifest) {
* manifest.content_scripts.push({
* matches: ["*://google.com/*"],
* css: ["content-scripts/some-example.css"],
* });
* }
* })
*/
transformManifest?: (manifest: Manifest.WebExtensionManifest) => void;
analysis?: {
/**
* Explicitly include bundle analysis when running `wxt build`. This can be overridden by the
* command line `--analysis` option.
*
* @default false
*/
enabled?: boolean;
/**
* When running `wxt build --analyze` or setting `analysis.enabled` to true, customize how the
* bundle will be visualized. See
* [`rollup-plugin-visualizer`](https://github.com/btd/rollup-plugin-visualizer#how-to-use-generated-files)
* for more details.
*
* @default "treemap"
*/
template?: PluginVisualizerOptions['template'];
};
}
export interface WxtInlineViteConfig
@@ -325,58 +365,75 @@ export type Entrypoint =
export type OnContentScriptStopped = (cb: () => void) => void;
export interface ContentScriptDefinition extends ExcludableEntrypoint {
matches: Manifest.ContentScript['matches'];
matches: PerBrowserOption<Manifest.ContentScript['matches']>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
* @default "documentIdle"
*/
runAt?: Manifest.ContentScript['run_at'];
runAt?: PerBrowserOption<Manifest.ContentScript['run_at']>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
* @default false
*/
matchAboutBlank?: Manifest.ContentScript['match_about_blank'];
matchAboutBlank?: PerBrowserOption<
Manifest.ContentScript['match_about_blank']
>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
* @default []
*/
excludeMatches?: Manifest.ContentScript['exclude_matches'];
excludeMatches?: PerBrowserOption<Manifest.ContentScript['exclude_matches']>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
* @default []
*/
includeGlobs?: Manifest.ContentScript['include_globs'];
includeGlobs?: PerBrowserOption<Manifest.ContentScript['include_globs']>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
* @default []
*/
excludeGlobs?: Manifest.ContentScript['exclude_globs'];
excludeGlobs?: PerBrowserOption<Manifest.ContentScript['exclude_globs']>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
* @default false
*/
allFrames?: Manifest.ContentScript['all_frames'];
allFrames?: PerBrowserOption<Manifest.ContentScript['all_frames']>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
* @default false
*/
matchOriginAsFallback?: boolean;
matchOriginAsFallback?: PerBrowserOption<boolean>;
/**
* See https://developer.chrome.com/docs/extensions/mv3/content_scripts/
* @default "ISOLATED"
*/
world?: 'ISOLATED' | 'MAIN';
world?: PerBrowserOption<'ISOLATED' | 'MAIN'>;
/**
* Customize how imported/generated styles are injected with the content script. Regardless of the
* mode selected, CSS will always be built and included in the output directory.
*
* - `"manifest"` - Include the CSS in the manifest, under the content script's `css` array.
* - `"manual"` - Exclude the CSS from the manifest. You are responsible for manually loading it
* onto the page. Use `browser.runtime.getURL("content-scripts/<name>.css")` to get the file's
* URL
*
* @default "manifest"
*/
cssInjectionMode?: PerBrowserOption<'manifest' | 'manual' | 'ui'>;
/**
* Main function executed when the content script is loaded.
*/
main(): void | Promise<void>;
main(ctx: ContentScriptContext): void | Promise<void>;
}
export interface BackgroundScriptDefintition extends ExcludableEntrypoint {
type?: 'module';
type?: PerBrowserOption<'module'>;
persistent?: PerBrowserOption<boolean>;
main(): void;
}
export type PerBrowserOption<T> = T | { [browser: TargetBrowser]: T };
export interface ExcludableEntrypoint {
/**
* List of target browsers to include this entrypoint in. Defaults to being included in all
@@ -438,6 +495,12 @@ export interface ConfigEnv {
* Configure how the browser starts up.
*/
export interface ExtensionRunnerConfig {
/**
* Whether or not to open the browser with the extension installed in dev mode.
*
* @default false
*/
disabled?: boolean;
/**
* @see https://extensionworkshop.com/documentation/develop/web-ext-command-reference/#browser-console
*/
+12 -1
View File
@@ -7,9 +7,13 @@ import {
TargetManifestVersion,
UserManifest,
ExtensionRunnerConfig,
ConfigEnv,
UserConfig,
} from './external';
import { UnimportOptions } from 'unimport';
import { ResolvedConfig } from 'c12';
import { Manifest } from 'webextension-polyfill';
import type { PluginVisualizerOptions } from 'rollup-plugin-visualizer';
export interface InternalConfig {
root: string;
@@ -25,9 +29,10 @@ export interface InternalConfig {
command: 'build' | 'serve';
browser: TargetBrowser;
manifestVersion: TargetManifestVersion;
env: ConfigEnv;
logger: Logger;
imports: false | Partial<UnimportOptions>;
vite: vite.InlineConfig;
vite: (env: ConfigEnv) => Promise<vite.InlineConfig> | vite.InlineConfig;
manifest: UserManifest;
fsCache: FsCache;
server?: WxtDevServer;
@@ -39,6 +44,12 @@ export interface InternalConfig {
ignoredSources: string[];
sourcesRoot: string;
};
transformManifest: (manifest: Manifest.WebExtensionManifest) => void;
analysis: {
enabled: boolean;
template: NonNullable<PluginVisualizerOptions['template']>;
};
userConfigMetadata: Omit<ResolvedConfig<UserConfig>, 'config'>;
}
export type EntrypointGroup = Entrypoint | Entrypoint[];
+26 -1
View File
@@ -1,5 +1,9 @@
import { describe, it, expect } from 'vitest';
import { getEntrypointName, getEntrypointOutputFile } from '../entrypoints';
import {
getEntrypointName,
getEntrypointOutputFile,
resolvePerBrowserOption,
} from '../entrypoints';
import { Entrypoint } from '../../types';
import { resolve } from 'path';
@@ -49,4 +53,25 @@ describe('Entrypoint Utils', () => {
expect(actual).toBe(expected);
});
});
describe('resolvePerBrowserOption', () => {
it('should return the value directly', () => {
expect(resolvePerBrowserOption('some-string', '')).toEqual('some-string');
expect(resolvePerBrowserOption(false, '')).toEqual(false);
expect(resolvePerBrowserOption([1], '')).toEqual([1]);
expect(resolvePerBrowserOption(['string'], '')).toEqual(['string']);
});
it('should return the value for the specific browser', () => {
expect(resolvePerBrowserOption({ a: 'one', b: 'two' }, 'a')).toEqual(
'one',
);
expect(resolvePerBrowserOption({ c: ['one'], d: ['two'] }, 'c')).toEqual([
'one',
]);
expect(resolvePerBrowserOption({ c: false, d: true }, 'e')).toEqual(
undefined,
);
});
});
});
+26 -9
View File
@@ -1,5 +1,6 @@
import { Manifest } from 'webextension-polyfill';
import { ContentScriptEntrypoint } from '../types';
import { ContentScriptEntrypoint, InternalConfig } from '../types';
import { resolvePerBrowserOption } from './entrypoints';
/**
* Returns a unique and consistent string hash based on a content scripts options.
@@ -35,18 +36,34 @@ export function hashContentScriptOptions(
export function mapWxtOptionsToContentScript(
options: ContentScriptEntrypoint['options'],
config: InternalConfig,
): Omit<Manifest.ContentScript, 'js' | 'css'> {
return {
matches: options.matches,
all_frames: options.allFrames,
match_about_blank: options.matchAboutBlank,
exclude_globs: options.excludeGlobs,
exclude_matches: options.excludeMatches,
include_globs: options.includeGlobs,
run_at: options.runAt,
matches: resolvePerBrowserOption(options.matches, config.browser),
all_frames: resolvePerBrowserOption(options.allFrames, config.browser),
match_about_blank: resolvePerBrowserOption(
options.matchAboutBlank,
config.browser,
),
exclude_globs: resolvePerBrowserOption(
options.excludeGlobs,
config.browser,
),
exclude_matches: resolvePerBrowserOption(
options.excludeMatches,
config.browser,
),
include_globs: resolvePerBrowserOption(
options.includeGlobs,
config.browser,
),
run_at: resolvePerBrowserOption(options.runAt, config.browser),
// @ts-expect-error: untyped chrome options
match_origin_as_fallback: options.matchOriginAsFallback,
match_origin_as_fallback: resolvePerBrowserOption(
options.matchOriginAsFallback,
config.browser,
),
world: options.world,
};
}
+13 -1
View File
@@ -1,4 +1,4 @@
import { Entrypoint } from '../types';
import { Entrypoint, PerBrowserOption, TargetBrowser } from '../types';
import path, { relative, resolve } from 'node:path';
import { normalizePath } from './paths';
@@ -34,3 +34,15 @@ export function getEntrypointBundlePath(
relative(outDir, getEntrypointOutputFile(entrypoint, ext)),
);
}
/**
* Given an entrypoint option, resolve it's value based on a target browser.
*/
export function resolvePerBrowserOption<T>(
option: PerBrowserOption<T>,
browser: TargetBrowser,
): T {
if (typeof option === 'object' && !Array.isArray(option))
return (option as any)[browser];
return option;
}
+36 -24
View File
@@ -30,13 +30,15 @@ export async function getInternalConfig(
// Load user config
let userConfig: UserConfig = {};
let userConfigMetadata: InternalConfig['userConfigMetadata'] | undefined;
if (inlineConfig.configFile !== false) {
const loaded = await loadConfig<UserConfig>({
const { config: loadedConfig, ...metadata } = await loadConfig<UserConfig>({
name: 'wxt',
cwd: inlineConfig.root ?? process.cwd(),
rcFile: false,
});
userConfig = loaded.config ?? {};
userConfig = loadedConfig ?? {};
userConfigMetadata = metadata;
}
// Merge it into the inline config
@@ -51,7 +53,8 @@ export async function getInternalConfig(
const browser = mergedConfig.browser ?? 'chrome';
const manifestVersion =
mergedConfig.manifestVersion ?? (browser == 'firefox' ? 2 : 3);
mergedConfig.manifestVersion ??
(browser === 'firefox' || browser === 'safari' ? 2 : 3);
const mode =
mergedConfig.mode ?? (command === 'build' ? 'production' : 'development');
const env: ConfigEnv = { browser, command, manifestVersion, mode };
@@ -75,7 +78,8 @@ export async function getInternalConfig(
cwd: root,
globalRc: true,
rcFile: '.webextrc',
overrides: mergedConfig.runner,
overrides: inlineConfig.runner,
defaults: userConfig.runner,
});
const finalConfig: InternalConfig = {
@@ -83,6 +87,7 @@ export async function getInternalConfig(
command,
debug,
entrypointsDir,
env,
fsCache: createFsCache(wxtDir),
imports: mergedConfig.imports ?? {},
logger,
@@ -96,16 +101,22 @@ export async function getInternalConfig(
runnerConfig,
srcDir,
typesDir,
vite: {}, // Real value added after this object is initialized.
vite: () => ({}), // Real value added after this object is initialized.
wxtDir,
zip: resolveInternalZipConfig(root, mergedConfig),
transformManifest(manifest) {
userConfig.transformManifest?.(manifest);
inlineConfig.transformManifest?.(manifest);
},
analysis: {
enabled: mergedConfig.analysis?.enabled ?? false,
template: mergedConfig.analysis?.template ?? 'treemap',
},
userConfigMetadata: userConfigMetadata ?? {},
};
finalConfig.vite = await resolveInternalViteConfig(
env,
mergedConfig,
finalConfig,
);
finalConfig.vite = (env) =>
resolveInternalViteConfig(env, mergedConfig, finalConfig);
return finalConfig;
}
@@ -143,9 +154,9 @@ function mergeInlineConfig(
return vite.mergeConfig(user, inline);
};
const viteConfig = async (env: ConfigEnv): Promise<WxtViteConfig> => {
const user = await resolveViteConfig(env, userConfig.vite);
const inline = await resolveViteConfig(env, inlineConfig.vite);
return vite.mergeConfig(user, inline);
const user = await userConfig.vite?.(env);
const inline = await inlineConfig.vite?.(env);
return vite.mergeConfig(user ?? {}, inline ?? {});
};
const runner: InlineConfig['runner'] = vite.mergeConfig(
userConfig.runner ?? {},
@@ -172,16 +183,14 @@ function mergeInlineConfig(
srcDir: inlineConfig.srcDir ?? userConfig.srcDir,
vite: viteConfig,
zip,
analysis: {
enabled: inlineConfig.analysis?.enabled ?? userConfig.analysis?.enabled,
template:
inlineConfig.analysis?.template ?? userConfig.analysis?.template,
},
};
}
async function resolveViteConfig(
env: ConfigEnv,
vite: InlineConfig['vite'],
): Promise<WxtViteConfig> {
return await (typeof vite === 'function' ? vite(env) : vite ?? {});
}
function resolveInternalZipConfig(
root: string,
mergedConfig: InlineConfig,
@@ -211,13 +220,13 @@ async function resolveInternalViteConfig(
mergedConfig: InlineConfig,
finalConfig: InternalConfig,
) {
const internalVite: vite.InlineConfig = await resolveViteConfig(
env,
mergedConfig.vite,
);
const internalVite: vite.InlineConfig =
(await mergedConfig.vite?.(env)) ?? {};
internalVite.root = finalConfig.root;
internalVite.configFile = false;
internalVite.logLevel = 'warn';
internalVite.mode = env.mode;
internalVite.build ??= {};
internalVite.build.outDir = finalConfig.outDir;
@@ -236,6 +245,9 @@ async function resolveInternalViteConfig(
internalVite.plugins.push(plugins.devServerGlobals(finalConfig));
internalVite.plugins.push(plugins.tsconfigPaths(finalConfig));
internalVite.plugins.push(plugins.noopBackground());
if (finalConfig.analysis.enabled) {
internalVite.plugins.push(plugins.bundleAnalysis());
}
internalVite.define ??= {};
for (const global of getGlobals(finalConfig)) {
+13
View File
@@ -46,3 +46,16 @@ export function getGlobals(
},
];
}
export function getEntrypointGlobals(
config: InternalConfig,
entrypointName: string,
) {
return [
{
name: '__ENTRYPOINT__',
value: entrypointName,
type: `string`,
},
];
}

Some files were not shown because too many files have changed in this diff Show More