A vite plugin to inject locally file reference for web script like TamperMonkey or ScriptCat
npm install @yiero/vite-plugin-scriptcat-require-selfEnglish / 中文
Automatically injects references into UserScript headers for Web Script like TamperMonkey or ScriptCat, referencing the locally built file: // @require .
``bash`
npm install @yiero/vite-plugin-scriptcat-require-self -Dor
yarn add @yiero/vite-plugin-scriptcat-require-self -Dor
pnpm add @yiero/vite-plugin-scriptcat-require-self -D
| Parameter | Type | Description | Default |
| ---------- | --------- | ------------------------------------------------------------ | ------- |
| isInsert | boolean | Whether to inject references, can be controlled via environment variables | true |
Add the plugin to your vite.config.js:
`ts
import { defineConfig } from 'vite'
import requireSelfPlugin from '@yiero/vite-plugin-scriptcat-require-self'
export default defineConfig( ( env ) => {
/*
* Get the current build environment
/
const isDevelopment = env.mode === 'development';
plugins: [
// Other plugins...
// If in development environment, outputs true and automatically injects local file reference
// Otherwise outputs false and the plugin does nothing
requireSelfPlugin( isDevelopment )
],
})
`
---
Add to your package.json:
`json`
{
// Other configurations...
"scripts": {
"dev": "vite build --mode development",
"build": "vite build --mode production",
// Other commands...
}
}
The plugin automatically:
1. Identifies UserScript files by detecting the // ==UserScript== marker@require
2. Generates the absolute file URL for the output script
3. Checks if a self-referencing directive already exists// @require
4. Injects before the closing // ==/UserScript== marker (if it doesn't exist)
Before processing:
`js
// ==UserScript==
// @name My Script
// @namespace https://example.com
// @version 1.0
// ==/UserScript==
console.log('Hello from UserScript!');
`
After building:
`js
// ==UserScript==
// @name My Script
// @namespace https://example.com
// @version 1.0
// @require file:///project-path/dist/script.js
// ==/UserScript==
console.log('Hello from UserScript!');
``
Contributions are welcome! Please submit issues or PRs via GitHub.
GPL-3 © AliubYiero