Skip to content
Source
Sign inSign up
TanStack/devtools
Open History to see the last commit

tsup-solid-v2.ts

80 lines2.8 KB

1// @ts-nocheck - untyped babel imports for the custom Solid 2 build plugin
2​
3import { readFile } from 'node:fs/promises'
4import { parse } from 'node:path'
5import { transformAsync } from '@babel/core'
6import ts from '@babel/preset-typescript'
7import solid from '@solidjs/babel-plugin'
8import type { Options } from 'tsup'
9​
10type Plugin = NonNullable<Options['esbuildPlugins']>[number]
11​
12/**
13 * Compiles JSX with `@solidjs/babel-plugin`, the Solid 2 compiler.
14 * `tsup-preset-solid`'s own esbuild plugin targets Solid 1.
15 */
16function solidV2Plugin(generate: 'dom' | 'ssr'): Plugin {
17 return {
18 name: 'esbuild:solid-v2',
19 setup(build) {
20 build.onLoad({ filter: /\.(t|j)sx$/ }, async (args) => {
21 const source = await readFile(args.path, { encoding: 'utf-8' })
22 const { name, ext } = parse(args.path)
23 const result = await transformAsync(source, {
24 presets: [[ts, {}]],
25 plugins: [[solid, { generate }]],
26 filename: name + ext,
27 sourceMaps: 'inline',
28 })
29 if (result?.code == null) {
30 throw new Error('No result was provided from Babel')
31 }
32 return { contents: result.code, loader: 'js' }
33 })
34 },
35 }
37​
38/**
39 * Swaps the Solid 1 compiler in `tsup-preset-solid`'s options for the Solid 2
40 * one. The preset marks its server build with `platform: 'node'`.
41 *
42 * With `bundleSolid`, Solid and the listed packages that use it go into the
43 * output, so the package runs on its own copy of Solid. The app's Solid
44 * version and the bundler's `solid-js` dedupe then cannot change it.
45 */
46export function withSolidV2(
47 options: Array<Options>,
48 { bundleSolid }: { bundleSolid?: Array<string | RegExp> } = {},
49): Array<Options> {
50 return options.map((option) => {
51 const plugins = option.esbuildPlugins ?? []
52 const others = plugins.filter((plugin) => !plugin.name.includes('solid'))
53 if (others.length === plugins.length) return option
54 return {
55 ...option,
56 esbuildPlugins: [
57 solidV2Plugin(option.platform === 'node' ? 'ssr' : 'dom'),
58 ...others,
59 ],
60 ...(bundleSolid
61 ? {
62 noExternal: [/^solid-js(\/|$)/, /^@solidjs\//, ...bundleSolid],
63 // The production build of Solid, also in `dev.js`: the app's
64 // dev mode must not turn on Solid's dev checks for our code.
65 esbuildOptions(esOptions, context) {
66 option.esbuildOptions?.(esOptions, context)
67 esOptions.conditions = []
68 },
69 }
70 : {
71 // Resolve `isServer` and friends in the consumer's build, not ours.
72 external: [
73 ...(Array.isArray(option.external) ? option.external : []),
74 '@solidjs/web',
75 'solid-js',
76 ],
77 }),
78 }
79 })