基于 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
,如下配置:
type ExternalGlobal = Record<string, string> | string[]
const options = {
externalGlobals: ['vue'],
// externalGlobals: { vue: 'Vue' }
}
// =>
const rollupOptions = {
external: ['vue']
output: {
globals: {
vue: 'Vue'
},
}
}
// @require https://unpkg.com/vue@3.2.20
自动分析代码中使用的 tampermonker
的 grant
,并加入声明中
生产构建模式将强制配置 config.build
:
- 入口为
src/main.js
或者src/main.ts
,由vite.config.(j|t)s
文件决定 - 构建的包名为
package.json
的name
(必须填写)属性的驼峰模式,构建的文件名也与其相关,文件打包格式为iife
,不压缩,不分离css
文件。 - 额外配置了
rollupOptions
,以支持其他功能。
在开发模式下,需要通过 script
标签注入 vite
的脚本,有些网站开启了 CSP(Content-Security-Policy)
,导致报错,可以安装Chrome
插件Disable Content-Security-Policy或者Always Disable Content-Security-Policy,来禁止CSP(Content-Security-Policy)
,在开发时开启插件即可(其他时间记得关闭以保证网页浏览的安全性)。