vite-plugin-monkey
A vite plugin server and build your.user.js for userscript engine like Tampermonkey and Violentmonkey, Greasemonkey, ScriptCat
Feature
- support Tampermonkey, Violentmonkey, Greasemonkey, ScriptCat, etc
- inject userscript comment to build bundle
- auto open *.user.js in default browser when userscript change
- external cdn url inject to userscript @require
- external module inject to userscript @resource
- use GM_api by ESM import with type hints
- intelligently collect GM_api that is used and automatically configure userscript @grant comment
- support
top level await
anddynamic import
in single file - when vite preview, auto open browser install dist.user.js
- full typescript support and vite feature
Quick Start
just like vite create
pnpm create monkey
# npm create monkey
# yarn create monkey
then you can choose the following template
JavaScript | TypeSript |
---|---|
empty (only js) | empty-ts (only ts) |
vanilla (js + css) | vanilla-ts (ts + css) |
vue | vue-ts |
react | react-ts |
preact | preact-ts |
svelte | svelte-ts |
solid | solid-ts |
Installation
pnpm add -D vite-plugin-monkey
# npm i -D vite-plugin-monkey
# yarn add -D vite-plugin-monkey
note: vite-plugin-monkey must be the last item
of plugin list
graph LR;
A(your code)-- vite build -- others plugins -->B(esm)
B -- vite-plugin-monkey -- vite build library mode --> C{has DynamicImport}
C -- yes --> D(systemjs)
C -- no --> E(iife)
Config
MonkeyOption Type
export type MonkeyOption = {
/**
* userscript entry file path
*/
entry: string;
userscript?: MonkeyUserScript;
format?: Format;
/**
* alias of vite-plugin-monkey/dist/client
* @default '$'
* @example
* // vite-env.d.ts for type hint
*
* // if you use default value `$`
* /// <reference types="vite-plugin-monkey/client" />
*
* // if you use other_alias
* declare module other_alias {
* export * from 'vite-plugin-monkey/dist/client';
* }
*/
clientAlias?: string;
server?: {
/**
* auto open install url in default browser when userscript comment change
*
* and set `viteConfig.server.open ??= monkeyConfig.server.open`
* @default
* process.platform == 'win32' || process.platform == 'darwin' // if platform is Win/Mac
*/
open?: boolean;
/**
* name prefix, distinguish server.user.js and build.user.js in monkey extension install list, if you not want prefix, set false
* @default 'server:'
*/
prefix?: string | ((name: string) => string) | false;
/**
* mount GM_api to unsafeWindow, not recommend it, you should use GM_api by ESM import, or use [unplugin-auto-import](https://github.com/antfu/unplugin-auto-import)
* @default false
* @example
* // if set true, you can use `vite-plugin-monkey/global` for type hint
* // vite-env.d.ts
* /// <reference types="vite-plugin-monkey/global" />
*/
mountGmApi?: boolean;
};
build?: {
/**
* build bundle userscript file name
*
* it should end with '.user.js'
* @default (package.json.name??'monkey')+'.user.js'
*/
fileName?: string;
/**
* build bundle userscript comment file name, this file is only include comment
*
* it can be used by userscript.updateURL, when checking for updates, just download this small file instead of downloading the entire script
*
* it should end with '.meta.js', if set false, will not generate this file
*
* if set true, will equal to fileName.replace(/\\.user\\.js$/,'.meta.js')
*
* @default false
*/
metaFileName?: string | boolean | ((fileName: string) => string);
/**
* this config can be array or object, array=Object.entries(object)
*
* if value is string or function, it or its return value is exportVarName
*
* if value is Array, the first [item or its return value] is exportVarName, the items after it all are url that is [require url]
*
* if module is unimported, plugin will not add require url to userscript
*
* @example
* { // map structure
* vue:'Vue',
* // if set this
* // you need manually set userscript.require = ['https://unpkg.com/vue@3.0.0/dist/vue.global.js'], when `vite build`
*
* vuex:['Vuex', (version, name)=>`https://unpkg.com/${name}@${version}/dist/vuex.global.js`],
* // plugin will auto add this url to userscript.require
*
* 'prettier/parser-babel': [
* 'prettierPlugins.babel',
* (version, name, importName) => {
* // name == `prettier`
* // importName == `prettier/parser-babel`
* const subpath = `${importName.split('/').at(-1)}.js`;
* return `https://cdn.jsdelivr.net/npm/${name}@${version}/${subpath}`;
* },
* ],
* // sometimes importName deffers from package name
* }
* @example
* [ // array structure, this example come from [playground/ex-vue-demi](https://github.com/lisonge/vite-plugin-monkey/tree/main/playground/ex-vue-demi)
* [
* 'vue',
* cdn
* .jsdelivr('Vue', 'dist/vue.global.prod.js')
* .concat('https://unpkg.com/vue-demi@latest/lib/index.iife.js')
* .concat(
* await util.fn2dataUrl(() => {
* window.Vue = Vue;
* }),
* ),
* ],
* ['pinia', cdn.jsdelivr('Pinia', 'dist/pinia.iife.prod.js')],
* [
* 'element-plus',
* cdn.jsdelivr('ElementPlus', 'dist/index.full.min.js'),
* ],
* ]
*/
externalGlobals?: ExternalGlobals;
/**
* according to final code bundle, auto inject GM_* or GM.* to userscript comment grant
*
* tree shaking code, then if code.includes('GM_xxx'), add \@grant GM_xxx to userscript
* @default true
*/
autoGrant?: boolean;
/**
* @deprecated use [viteConfig.build.cssMinify](https://vitejs.dev/config/build-options.html#build-cssminify) in vite>=4.2.0
*
* now minifyCss will not work
*/
minifyCss?: boolean;
/**
* @example
* { // resourceName default value is pkg.importName
* 'element-plus/dist/index.css': pkg=>`https://unpkg.com/${pkg.name}@${pkg.version}/${pkg.resolveName}`,
* 'element-plus/dist/index.css': {
* resourceName: pkg=>pkg.importName,
* resourceUrl: pkg=>`https://unpkg.com/${pkg.name}@${pkg.version}/${pkg.resolveName}`,
* loader: pkg=>{ // there are default loaders that support [css, json, the assets that vite support, ?url, ?raw] file/name suffix
* const css = GM_getResourceText(pkg.resourceName);
* GM_addStyle(css);
* return css;
* },
* nodeLoader: pkg=>{
* return [
* `export default (()=>{`,
* `const css = GM_getResourceText(${JSON.stringify(pkg.resourceName)});`,
* `GM_addStyle(css);`,
* `return css;`,
* `})();`
* ].join('');
* },
* },
* 'element-plus/dist/index.css': [
* (version, name, importName, resolveName)=>importName,
* (version, name, importName, resolveName)=>`https://unpkg.com/${name}@${version}/${resolveName}`,
* // for compat externalGlobals cdn function, if (version/name/importName/resolveName) == '', plugin will use their own default values
* ],
* 'element-plus/dist/index.css': cdn.jsdelivr(),
* }
*/
externalResource?: ExternalResource;
/**
* when use dynamic-import, plugin will use systemjs build your code
*
* `cdn.jsdelivr()[1]` example -> [dynamic-import.user.js](https://github.com/lisonge/vite-plugin-monkey/blob/7645b185605faf9b48c43116db5ea01726188e03/playground/dynamic-import/dist/dynamic-import.user.js)
*
* `'inline'` exmple -> [test-v3.user.js](https://github.com/lisonge/vite-plugin-monkey/blob/7645b185605faf9b48c43116db5ea01726188e03/playground/test-v3/dist/test-v3.user.js)
*
* @default
* cdn.jsdelivr()[1]
*/
systemjs?: 'inline' | Mod2UrlFn2;
};
};
CDN util for external
import { defineConfig } from 'vite';
import monkey, { cdn } from 'vite-plugin-monkey';
export default defineConfig({
plugins: [
monkey({
build: {
externalGlobals: {
react: cdn.jsdelivr('React', 'umd/react.production.min.js'),
},
externalResource: {
'element-plus/dist/index.css': cdn.jsdelivr(),
},
},
}),
],
});
there is the following cdn to use, full detail see cdn.ts
if you want use other cdn, you can see external-scripts
GM_api usage
ESM usage
we can use GM_api by esm module
// main.ts
import { GM_cookie, unsafeWindow, monkeyWindow, GM_addElement } from '$';
// $ is the default alias of vite-plugin-monkey/dist/client
// if you want use 'others', set monkeyConfig.clientAlias='others'
// whatever it is serve or build mode, monkeyWindow is always the window of [UserScript Scope]
console.log(monkeyWindow);
GM_addElement(document.body, 'div', { innerHTML: 'hello' });
// whatever it is serve or build mode, unsafeWindow is always host window
if (unsafeWindow == window) {
console.log('scope->host, host esm scope');
} else {
console.log('scope->monkey, userscript scope');
}
GM_cookie.list({}, (cookies, error) => {
if (error) {
console.log(error);
} else {
const [cookie] = cookies;
if (cookie) {
console.log(cookie);
}
}
});
Global variables usage
set monkeyConfig.server.mountGmApi=true
// vite.config.ts
import { defineConfig } from 'vite';
import monkey from 'vite-plugin-monkey';
export default defineConfig({
plugins: [
monkey({
// ...
server: { mountGmApi: true },
}),
],
});
GM_api will mount to the property of host window/globalThis
// main.ts
console.log(GM_cookie == globalThis.GM_cookie);
console.log({ GM_cookie, unsafeWindow, monkeyWindow, GM_addElement });
Auto import usage
// vite.config.ts
import { defineConfig } from 'vite';
import monkey, { util } from 'vite-plugin-monkey';
import AutoImport from 'unplugin-auto-import/vite';
export default defineConfig({
plugins: [
AutoImport({
imports: [util.unimportPreset],
}),
monkey({
// ...
}),
],
});
// main.ts
// auto import example
console.log({ GM_cookie, unsafeWindow, monkeyWindow, GM_addElement });
Example
test examples, see /playground
and preact/react/svelte/vanilla/vue/solid examples, see create-monkey
Some note
Work with other plugins
plugin will rebuild your code by generateBundle hook
please ensure that the order of the plugin is the last one
CSP
in vite serve
mode, the code entry is added as script to target host document.head, code need work between two origins
For http header csp
you can use Tampermonkey then open extension://iikmkjmpaadaobahmlepeloendndfphd/options.html#nav=settings
at Security
, set Modify existing content security policy (CSP) headers
to Remove entirely (possibly unsecure)
full detail see issues/1
and if you use Violentmonkey
/Greasemonkey
, you can solve it in the following ways
- chrome - Disable Content-Security-Policy
- edge - Disable Content-Security-Policy
- firefox - disable
security.csp.enable
in theabout:config
menu
For html csp
-
MITM modify html by https://wproxy.org/whistle/
-
if csp allow
*.xx.com
, you can setviteConfig.server.host=localhost.xx.com
and add127.0.0.1 localhost.xx.com
to your hosts file, if your need fake https ca, you can use mkcert -
by chrome-remote-interface issues/1#issuecomment-1236060681
Mixed IIFE and UMD at @require
the variable declared by var
from iife-cdn will not become the property of window at monkeyWindow scope, because monkeyWindow scope is not global scope
so if an umd lib is dependent on an iife lib, such as element-plus
is dependent on vue
, element-plus
cdn will not work
detail see issues/5 or greasyfork#1084
the solution is that we append a dataUrl script that will set iife-variable as the property of window after iife-cdn
import { defineConfig } from 'vite';
import monkey, { cdn, util } from 'vite-plugin-monkey';
export default defineConfig(async ({ command, mode }) => ({
plugins: [
monkey({
// ...
build: {
externalGlobals: {
vue: cdn.jsdelivr('Vue', 'dist/vue.global.prod.js').concat(
await util.fn2dataUrl(() => {
// @ts-ignore
window.Vue = Vue; // work with element-plus
}),
),
'element-plus': cdn.jsdelivr('ElementPlus', 'dist/index.full.min.js'),
},
},
}),
],
}));
Polyfill
when plugin works with vite legacy, it is necessary to set renderLegacyChunks=false
// vite.config.ts
import legacy from '@vitejs/plugin-legacy';
import { defineConfig } from 'vite';
import monkey from 'vite-plugin-monkey';
export default defineConfig({
plugins: [
legacy({
renderLegacyChunks: false,
modernPolyfills: true,
}),
monkey({
entry: './src/main.ts',
}),
],
});
Contribution
please commit your changes to dev branch