| 1 | import { createPlugin } from "../factory.ts"; |
| 2 | |
| 3 | const CLOUDFLARE_BUILT_IN_MODULES = [ |
| 4 | "cloudflare:email", |
| 5 | "cloudflare:node", |
| 6 | "cloudflare:sockets", |
| 7 | "cloudflare:workers", |
| 8 | "cloudflare:workflows", |
| 9 | ]; |
| 10 | |
| 11 | export const cloudflareExternalsPlugin = createPlugin( |
| 12 | "cloudflare-externals", |
| 13 | () => { |
| 14 | return { |
| 15 | rolldown: { |
| 16 | resolveId: { |
| 17 | filter: { id: /^cloudflare:/ }, |
| 18 | handler(id) { |
| 19 | if (!CLOUDFLARE_BUILT_IN_MODULES.includes(id)) { |
| 20 | return; |
| 21 | } |
| 22 | |
| 23 | return { |
| 24 | id, |
| 25 | external: true, |
| 26 | }; |
| 27 | }, |
| 28 | }, |
| 29 | }, |
| 30 | vite: { |
| 31 | enforce: "pre", |
| 32 | configEnvironment(name) { |
| 33 | if (name === "client") { |
| 34 | // Some frameworks allow users to mix client and server code in the same file and then extract the server code. |
| 35 | // As the dependency optimization may happen before the server code is extracted, we should exclude Cloudflare built-ins from client optimization. |
| 36 | return { optimizeDeps: { exclude: CLOUDFLARE_BUILT_IN_MODULES } }; |
| 37 | } |
| 38 | return { |
| 39 | resolve: { |
| 40 | builtins: CLOUDFLARE_BUILT_IN_MODULES, |
| 41 | }, |
| 42 | optimizeDeps: { |
| 43 | exclude: CLOUDFLARE_BUILT_IN_MODULES, |
| 44 | }, |
| 45 | }; |
| 46 | }, |
| 47 | }, |
| 48 | }; |
| 49 | }, |
| 50 | ); |