To build a library that can be used by vite-plugin-monkey users via npm, follow these steps:
- Import GM_api from the client: In your library code, import
GM_api from vite-plugin-monkey/dist/client. - Exclude the client during build: When building your library (e.g., using
tsup), exclude vite-plugin-monkey/dist/client from the bundle so users can provide their own implementation. - Provide an IIFE fallback: To support users who want to use your library via
@require, build an IIFE version where you alias vite-plugin-monkey/dist/client to vite-plugin-monkey/dist/native. This ensures the library uses the native implementation when bundled as an IIFE.
This approach allows your library to be used seamlessly both as an npm dependency in a Vite project and as a standalone script via @require.
// /src/index.ts
import { GM_setValue } from 'vite-plugin-monkey/dist/client';
export const setValue = (name: string, value: unknown) => {
console.log('you invoke setValue', name, value);
GM_setValue(name, value);
};
// tsup.config.ts
import { defineConfig } from 'tsup';
const outExtension = (ctx: { format: 'esm' | 'cjs' | 'iife' }) => ({
js: { esm: '.mjs', cjs: '.cjs', iife: '.iife.js' }[ctx.format],
});
export default defineConfig([
{
// for vite import
entry: ['src/index.ts'],
outDir: 'dist',
sourcemap: true,
platform: 'browser',
outExtension,
dts: true,
format: ['esm'],
external: ['vite-plugin-monkey/dist/client'],
},
{
// for userscript @require
entry: ['src/index.ts'],
outDir: 'dist',
sourcemap: true,
platform: 'browser',
outExtension,
dts: false,
format: ['iife'],
minify: true,
globalName: `GmExtra`,
target: 'es2015',
esbuildOptions: (options) => {
options.alias = {
'vite-plugin-monkey/dist/client': 'vite-plugin-monkey/dist/native',
};
},
},
]);