一、背景
在使用@crxjs/vite-plugin一段時間後,開發發了welibrary等圖書館插件,為了進一步推廣插件計劃支持Chrome、Edge瀏覽器之外的Firefox,為此耗費了不少時間用於調整配置,初步結論如下,
1)Firefox對mv2版本支持更多,mv3版本有諸多限制,@crxjs/vite-plugin等工具打包後的產物可能無法運行
2)雖然Firefox支持chrome全局變量,但是使用webextension-polyfill支持跨瀏覽器更加順暢
二、選擇新框架
無意中發現了wxt.dev,它的看法和我調研後兩個結論如此接近,而且它還是battery ready形式的設計。
通過約定代碼組織形式,然後解析生成manifest.json這點就別出新意,業務代碼和配置功能融合一體,更加模塊化,約定大於配置實際上就對開發人員減負不少。
還有多入口的理解,這是其他瀏覽器插件沒有做到的,可以看出作者對瀏覽器插件架構的設計有深刻的理解。
還有type-safety, auto-import,甚至還對storage進行了重新設計,最後當然是不同瀏覽器的debug和打包功能了,這些這個框架都支持得很絲滑。
三、開發過程
結合官網的文檔,https://wxt.dev
pnpx wxt@latest init <project-name>
然後選擇vue和pnpm選項
生成的樣板代碼如下,
<rootDir>
├─src/
│ └─ entries/
│ ├─ background.ts
│ └─ ...
└─wxt.config.ts
3.1開發content scripts
按照官網推薦的目錄組織不做改動,在entrypoints新建xxx.content.ts,比如entrypoints/csdn.content.ts
import { createApp } from'vue'
importAppfrom'./components/Trojan.vue'
exportdefaultdefineContentScript({
matches: ['https://*.blog.csdn.net/**'],
main() {
constel = document.createElement('div')
document.body.append(el)
createApp(App).mount(el)
},
})
這個做法最終產生的內容包含一段manifest.json的配置,
Content_scripts: [
{"matches":["https://*.blog.csdn.net/**"],"css":["content-scripts/csdn.css"],"js":["content-scripts/csdn.js"]}]
在Vue文件裏面的內容就和普通的Vue開發沒有什麼區別了。
除了defineContentScript還有defineBackground
3.2 調整manifest配置
如果在整個插件項目中使用到了storage權限,但是從xxx.content.ts等入口文件中又沒有看到可以配置的,這個時候就需要調整wxt.config.ts配置了,
export default defineConfig({
manifest: {
permissions: ['storage', 'tabs'],
},
});
如果要支持mv3和mv2,涉及web_accessible_resources、host_permissions到等屬性時要特殊處理下,建議使用
manifest: ({ manifestVersion }) => ({}) function配置形式,
1)web_accessible_resources
在mv3中web_accessible_resources的結構,
[
{
resources: ['*.png', '*.svg'],
matches: ['<all_urls>'],
},
]
在mv2中結構是['.png', '.svg']
2)host_permissions
在mv2中沒有host_permissions,所以必須合併到permissions的末尾。
3)還要update_url
這個是為了支持Firefox插件的要求,舉例,
update_url:'https://honwhy.wang/projects/',
四、前端工程化增強
這個框架還有缺少關於eslint和格式化等配置,在此做些補充。
在我同事的推薦之下,參考這篇文章,https://antfu.me/posts/why-not-prettier,最終的配置很簡單
pnpm add @antfu/eslint-config -D
新增<rootDir>/eslint.config.js配置文件,
importantfufrom'@antfu/eslint-config'
exportdefaultantfu({
//
customizations
rules: { 'no-console':'off' },
})
另外為了解決css格式等問題,建議在vscode中安裝Prettier,在工程中配置.editorconfig搭配使用,<rootDir>/.editorconfig
# EditorConfig
helps developers define and maintain consistent
# coding styles
between different editors and IDEs
#
editorconfig.org
root = true
[*]
# Change these
settings to your own preference
indent_style = space
indent_size = 2
# I recommend
you to keep these unchanged
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 80
[*.md]
trim_trailing_whitespace = false
調整package.json
“scripts” {
"lint": "eslint .",
"lint:fix": "eslint .--fix"
}
最終整體目錄
附錄
[1]wxt.dev, https://wxt.dev
[2] Why I don't use Prettier, https://antfu.me/posts/why-not-prettier