基于 vite
的 tampermonkey
开发构建插件。
- 通过
package.json
的tampermonkey
属性配置tampermonkey
的头部描述。 - 构建生产时会支持自动分析代码用到的
grant
,开发模式则默认导入所有,并且把所有的grant
方法加入到unsafeWindow
- 可通过简单配置,把引入的外部包
require
化,自动引入unpkg.com
的CDN
,详情见下面的插件配置
yarn add vite-plugin-tampermonkey -D
npm install vite-plugin-tampermonkey -D
import { defineConfig } from 'vite'
import tampermonkey from 'vite-plugin-tampermonkey'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
tampermonkey({
externalGlobals: ['vue']
})
],
})
外部包配置,比如 vue
,axios
等,减少打包体积,并且会自动声明 require
,require 会按数组(或者Object.keys
)的顺序生成,如下配置:
type AnyObj = Record<string, string>
interface ExternalGlobalItem {
/**包名,可以是代码(type = code),或者链接 */
pkgName: string
varName?: string
type?: 'code' | 'package'
path?: string
}
export type ExternalGlobal =
| AnyObj
| (string | ExternalGlobalItem | [pkgName: string, varName: string])[]
const options = {
externalGlobals: ['vue'],
// externalGlobals: { vue: 'Vue' }
}
// =>
const rollupOptions = {
external: ['vue']
output: {
globals: {
vue: 'Vue'
},
}
}
// @require https://unpkg.com/vue@3.2.20
请点击此处查看更多高级用法,可配置路径,代码,链接等。
配置后,依旧可以使用 externalGlobals
选项的高级用法覆盖。
自动分析代码中使用的 tampermonker
的 grant
,并加入声明中
生产构建模式将强制配置 config.build
:
- 入口为
src/main.js
或者src/main.ts
,由vite.config.(j|t)s
文件决定 - 构建的包名为
package.json
的name
(必须填写)属性的驼峰模式,构建的文件名也与其相关,文件打包格式为iife
,不压缩,不分离css
文件。 - 额外配置了
rollupOptions
,以支持其他功能。
如果你有使用 Unocss 的话,需要把 UnoCSS
插件放置在本插件之前,确保在 UnoCSS
处理完样式后再由本插件来合并到入口文件内。
import { defineConfig } from 'vite'
import tampermonkey from 'vite-plugin-tampermonkey'
import Unocss from 'unocss/vite'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
Unocss(),
tampermonkey({
externalGlobals: ['vue']
})
],
})
在开发模式下,需要通过 script
标签注入 vite
的脚本,有些网站开启了 CSP(Content-Security-Policy)
,导致报错,可以安装Chrome
插件Disable Content-Security-Policy或者Always Disable Content-Security-Policy,来禁止CSP(Content-Security-Policy)
,在开发时开启插件即可(其他时间记得关闭以保证网页浏览的安全性)。