ca29537bbc
Generalized the background logic so it can be reused with mulitple entrypoint types
36 lines
1.1 KiB
TypeScript
36 lines
1.1 KiB
TypeScript
import { Plugin } from 'vite';
|
|
import { Entrypoint } from '../types';
|
|
import fs from 'fs-extra';
|
|
import { resolve } from 'path';
|
|
|
|
/**
|
|
* Wraps a user's entrypoint with a vitual version with additional logic.
|
|
*/
|
|
export function virtualEntrypoin(type: Entrypoint['type']): Plugin {
|
|
const virtualId = `virtual:exvite-${type}?`;
|
|
const resolvedVirtualId = `\0${virtualId}`;
|
|
|
|
return {
|
|
name: `exvite:virtual-entrypoint`,
|
|
resolveId(id) {
|
|
// Id doesn't start with prefix, it looks like this:
|
|
// /path/to/project/virtual:background?/path/to/project/entrypoints/background.ts
|
|
const index = id.indexOf(virtualId);
|
|
if (index === -1) return;
|
|
|
|
const inputPath = id.substring(index + virtualId.length);
|
|
return resolvedVirtualId + inputPath;
|
|
},
|
|
async load(id) {
|
|
if (!id.startsWith(resolvedVirtualId)) return;
|
|
|
|
const inputPath = id.replace(resolvedVirtualId, '');
|
|
const template = await fs.readFile(
|
|
resolve(`node_modules/exvite/templates/virtual-${type}.ts`),
|
|
'utf-8',
|
|
);
|
|
return template.replaceAll('{{moduleId}}', inputPath);
|
|
},
|
|
};
|
|
}
|