|
| 1 | +import * as esModuleLexer from "es-module-lexer"; |
| 2 | +import { |
| 3 | + type FilterPattern, |
| 4 | + type Plugin, |
| 5 | + type ResolvedConfig, |
| 6 | + createFilter, |
| 7 | +} from "vite"; |
| 8 | +import { name as packageName } from "../package.json"; |
| 9 | + |
| 10 | +// similar to remix's https://github.com/remix-run/remix/blob/80c6842f547b7e83b58f1963894b07ad18c2dfe2/packages/remix-dev/compiler/plugins/emptyModules.ts#L10 |
| 11 | +// but for vite, we needs to fake esm exports so we use es-module-lexer to extract export names. |
| 12 | + |
| 13 | +export function viteNullExportPlugin(pluginOpts?: { |
| 14 | + serverOnly?: FilterPattern; |
| 15 | + serverOnlyExclude?: FilterPattern; |
| 16 | + clientOnly?: FilterPattern; |
| 17 | + clientOnlyExclude?: FilterPattern; |
| 18 | + debug?: boolean; |
| 19 | +}): Plugin { |
| 20 | + const serverOnly = pluginOpts?.serverOnly |
| 21 | + ? createFilter(pluginOpts?.serverOnly, pluginOpts?.serverOnlyExclude) |
| 22 | + : () => false; |
| 23 | + const clientOnly = pluginOpts?.clientOnly |
| 24 | + ? createFilter(pluginOpts?.clientOnly, pluginOpts?.clientOnlyExclude) |
| 25 | + : () => false; |
| 26 | + |
| 27 | + let logger!: ResolvedConfig["logger"]; |
| 28 | + |
| 29 | + return { |
| 30 | + // we don't enforce "pre" since es-module-lexer cannot reliably parse typescript file. |
| 31 | + // so we rely on vite's default typescript transpilation. |
| 32 | + |
| 33 | + name: packageName, |
| 34 | + |
| 35 | + configResolved(config) { |
| 36 | + logger = config.logger; |
| 37 | + }, |
| 38 | + |
| 39 | + async transform(code, id, options) { |
| 40 | + if (options?.ssr ? clientOnly(id) : serverOnly(id)) { |
| 41 | + if (pluginOpts?.debug) { |
| 42 | + logger.info( |
| 43 | + `[DEBUG:${packageName}:${ |
| 44 | + options?.ssr ? "clientOnly" : "serverOnly" |
| 45 | + }] ${id}` |
| 46 | + ); |
| 47 | + } |
| 48 | + await esModuleLexer.init; |
| 49 | + const [_import, exports] = esModuleLexer.parse(code); |
| 50 | + return exports |
| 51 | + .map((e) => |
| 52 | + e.n === "default" |
| 53 | + ? `export default null;\n` |
| 54 | + : `export var ${e.n} = null;\n` |
| 55 | + ) |
| 56 | + .join(""); |
| 57 | + } |
| 58 | + return undefined; |
| 59 | + }, |
| 60 | + }; |
| 61 | +} |
0 commit comments