|
| 1 | +import { Plugin, PluginBuild } from 'esbuild'; |
| 2 | +import { DEPLOY_URL } from '../custom-loader/custom-loader'; |
| 3 | + |
| 4 | + |
| 5 | +export function serverSSRPlugin(deployUrl: string): Plugin { |
| 6 | + return { |
| 7 | + name: 'serverSSRPlugin', |
| 8 | + setup(build: PluginBuild) { |
| 9 | + if (build.initialOptions.platform !== 'node') return; |
| 10 | + const serverSrrName = 'server.ssr'; |
| 11 | + |
| 12 | + build.initialOptions.entryPoints = { |
| 13 | + ...build.initialOptions.entryPoints, |
| 14 | + [serverSrrName]: serverSrrName, |
| 15 | + }; |
| 16 | + build.initialOptions.external = [ |
| 17 | + ...build.initialOptions.external, |
| 18 | + './server.mjs', |
| 19 | + ]; |
| 20 | + build.onResolve( |
| 21 | + { filter: new RegExp('^' + serverSrrName) }, |
| 22 | + ({ kind, path }) => { |
| 23 | + if (kind !== 'entry-point') { |
| 24 | + return null; |
| 25 | + } |
| 26 | + return { |
| 27 | + path: path, |
| 28 | + namespace: serverSrrName, |
| 29 | + }; |
| 30 | + } |
| 31 | + ); |
| 32 | + build.onLoad({ filter: /./, namespace: serverSrrName }, () => { |
| 33 | + return { |
| 34 | + contents: ` |
| 35 | + import {register} from "node:module"; |
| 36 | + const { port1, port2 } = new MessageChannel(); |
| 37 | + register('./custom-loader.mjs', { |
| 38 | + parentURL: import.meta.url, |
| 39 | + data: { port: port2 }, |
| 40 | + transferList: [port2], |
| 41 | + }); |
| 42 | + port1.postMessage({ kind: '${DEPLOY_URL}', result: '${deployUrl}' }); |
| 43 | + import('./server.mjs') |
| 44 | + `, |
| 45 | + loader: 'js', |
| 46 | + }; |
| 47 | + }); |
| 48 | + }, |
| 49 | + }; |
| 50 | +} |
0 commit comments