如何压缩浏览器扩展中web_accessible_resources内的脚本?
如何让CRXJS构建时压缩web_accessible_resources中的注入脚本
你遇到的问题是CRXJS默认将web_accessible_resources中的资源视为静态文件直接复制,不会经过Vite的打包压缩流程。要解决这个问题,需要把注入脚本纳入Vite的构建体系,让Vite对其进行处理,具体步骤如下:
步骤1:将注入脚本添加为Vite构建入口
修改vite.config.ts,在rollupOptions.input中添加src/injection.js作为额外的构建入口,这样Vite会对它进行打包、压缩,并生成带hash的输出文件:
// vite.config.ts import { defineConfig } from 'vite' import { crx } from '@crxjs/vite-plugin' import { svelte } from '@sveltejs/vite-plugin-svelte' import path from 'path' import sveltePreprocess from 'svelte-preprocess' import manifest from './src/manifest'; export default defineConfig(({ mode }) => { const production = mode === 'production' return { build: { minify: true, emptyOutDir: true, outDir: 'build', rollupOptions: { input: { // 添加injection脚本作为构建入口 injection: path.resolve(__dirname, 'src/injection.js'), }, output: { // 统一资源输出命名规则(包含hash避免缓存问题) assetFileNames: 'assets/[name]-[hash][extname]', chunkFileNames: 'assets/[name]-[hash][extname]', entryFileNames: 'assets/[name]-[hash][extname]', }, }, }, plugins: [ crx({ manifest }), svelte({ compilerOptions: { dev: !production, }, preprocess: sveltePreprocess(), }), ], resolve: { alias: { '@': path.resolve(__dirname, 'src'), }, }, } })
步骤2:更新manifest中的资源路径
修改manifest.ts的web_accessible_resources,将资源路径改为Vite构建后的输出路径(因为输出文件名带hash,所以用通配符匹配):
// manifest.ts import { defineManifest } from '@crxjs/vite-plugin' export default defineManifest({ "manifest_version": 3, "permissions": ["storage"], "content_scripts": [ { "run_at": "document_start", "matches": [ "https://*.example.com/*" ], "js": [ "src/content/content.ts" ] } ], "action": { "default_popup": "src/popup.html" }, "background": { "service_worker": "src/background/background.ts" }, "icons": { "48": "assets/icons/icon48.png", }, "web_accessible_resources": [ { "matches": [ "https://*.example.com/*" ], "resources": [ "assets/injection-*.js" // 匹配构建后的带hash的注入脚本 ], "use_dynamic_url": true, } ], })
步骤3:确保content script正确引用注入脚本
在你的content script中,使用chrome.runtime.getURL获取构建后的脚本的正确URL,比如:
// src/content/content.ts const injectScript = () => { const script = document.createElement('script'); // 因为配置了use_dynamic_url,Chrome会自动解析通配符对应的实际文件 script.src = chrome.runtime.getURL('assets/injection-*.js'); script.onload = () => script.remove(); document.documentElement.appendChild(script); }; injectScript();
这样构建后,injection.js会被Vite压缩处理,生成带hash的文件并输出到build/assets目录,同时manifest中的配置也能正确匹配到这个文件。
内容的提问来源于stack exchange,提问作者Viewed
相关产品推荐
相关产品推荐

