svelte-bun 0.1.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -91,6 +91,8 @@ instead.
91
91
  every option, `svelte.config.js`, custom renderers, and the preload
92
92
  - [Compile API](https://github.com/metonym/svelte-bun/blob/master/docs/compile.md):
93
93
  `compileFile()` and `scanImports()`, for another host
94
+ - [Recipes](https://github.com/metonym/svelte-bun/blob/master/docs/recipes.md):
95
+ prerendering, hydrating, build-time data, CSS types
94
96
  - [Compared](https://github.com/metonym/svelte-bun/blob/master/docs/compared.md):
95
97
  what differs from `bun-plugin-svelte`, and how it was measured
96
98
 
package/docs/options.md CHANGED
@@ -17,7 +17,7 @@ await Bun.build({
17
17
  | Option | Sets | Default |
18
18
  | :--- | :--- | :--- |
19
19
  | `root` | where `svelte.config.js` and `svelte` resolve from | the working directory |
20
- | `production` | no development checks or HMR, and Svelte's dev-only runtime code dropped | `NODE_ENV === "production"` |
20
+ | `production` | no development checks or HMR, Svelte's dev-only runtime code dropped, and `process.env.NODE_ENV` defined as `"production"` | `NODE_ENV === "production"` |
21
21
  | `side` | `"client"` or `"server"` output | what the dev server asks for, else `"client"` |
22
22
  | `preprocess` | Svelte preprocessors | `svelte.config.js`'s |
23
23
  | `compilerOptions` | passed to Svelte's `compile()` | `svelte.config.js`'s |
@@ -52,6 +52,15 @@ a relative `@import` in the component's `<style>` resolves from the
52
52
  component's directory.
53
53
  `"injected"` puts the CSS in the component's JavaScript instead.
54
54
 
55
+ ## Library barrels
56
+
57
+ A component library's `index.js` often only re-exports its components.
58
+ Bun drops the components an app doesn't use, but keeps their CSS,
59
+ so svelte-bun rewrites a component's named import from such a barrel,
60
+ `import { Highlight } from "svelte-highlight"`,
61
+ to the file it re-exports.
62
+ A barrel that does anything else is left alone.
63
+
55
64
  ## `load`
56
65
 
57
66
  `load(path)` returns the source to compile for a `.svelte` file,
@@ -0,0 +1,92 @@
1
+ # Recipes
2
+
3
+ Recipes are complete setups for jobs svelte-bun leaves to the app:
4
+ prerendering, starting the client, build-time data, and types.
5
+
6
+ ## Prerender a page
7
+
8
+ Build the app, build the component for the server, render it,
9
+ and put its `head` and `body` into the built page:
10
+
11
+ ```ts
12
+ // build.ts
13
+ import { svelte } from "svelte-bun";
14
+
15
+ await Bun.build({
16
+ entrypoints: ["index.html"],
17
+ outdir: "dist",
18
+ minify: true,
19
+ plugins: [svelte({ production: true })],
20
+ });
21
+
22
+ const server = await Bun.build({
23
+ entrypoints: ["src/App.svelte"],
24
+ outdir: "dist/.server",
25
+ target: "bun",
26
+ plugins: [svelte({ production: true, side: "server" })],
27
+ });
28
+ const { render } = await import("svelte/server");
29
+ const { default: App } = await import(server.outputs[0].path);
30
+ const { head, body } = render(App);
31
+
32
+ const page = Bun.file("dist/index.html");
33
+ const html = (await page.text())
34
+ .replace("</head>", `${head}</head>`)
35
+ .replace('<div id="app"></div>', `<div id="app">${body}</div>`);
36
+ await Bun.write(page, html);
37
+ ```
38
+
39
+ `index.html` holds an empty `<div id="app"></div>` for the markup.
40
+
41
+ ## Start the client
42
+
43
+ Hydrate the target when it holds prerendered markup,
44
+ and mount when it doesn't:
45
+
46
+ ```ts
47
+ // src/main.ts
48
+ import { hydrate, mount } from "svelte";
49
+
50
+ import App from "./App.svelte";
51
+
52
+ const target = document.querySelector("#app") ?? document.body;
53
+ (target.firstChild ? hydrate : mount)(App, { target });
54
+ ```
55
+
56
+ ## Build-time data with a macro
57
+
58
+ A Bun macro runs while the app builds,
59
+ and its return value is inlined into the output:
60
+
61
+ ```ts
62
+ // src/data.ts
63
+ import { loadExamples } from "./examples.js" with { type: "macro" };
64
+
65
+ export const examples = loadExamples();
66
+ ```
67
+
68
+ With `production: true`, svelte-bun defines `process.env.NODE_ENV` as
69
+ `"production"` for the build, so a macro sees it too; without a define,
70
+ Bun runs macros with `development`.
71
+ Write the macro in JavaScript, with a `.d.ts` beside it:
72
+ a TypeScript macro brings its imports into the client's typecheck.
73
+
74
+ ## Import CSS from TypeScript
75
+
76
+ Svelte's types declare `*.svelte` modules,
77
+ and Bun's don't declare `*.css`, so an app that imports a stylesheet
78
+ declares it once:
79
+
80
+ ```ts
81
+ // src/env.d.ts
82
+ declare module "*.css";
83
+ ```
84
+
85
+ ## Not supported
86
+
87
+ - Source maps: Bun drops a plugin's source map,
88
+ so an error in a component points at its compiled line.
89
+
90
+ ## Related
91
+
92
+ - [Options](options.md): what `production` and the other options do
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "svelte-bun",
3
- "version": "0.1.1",
3
+ "version": "0.2.1",
4
4
  "description": "Svelte for Bun.build and Bun's dev server.",
5
5
  "license": "MIT",
6
6
  "author": "Eric Liu (https://github.com/metonym)",
package/src/barrel.ts ADDED
@@ -0,0 +1,112 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+
4
+ // Each barrel's exports: name -> the file and name it re-exports, or
5
+ // undefined for a module that does more than re-export.
6
+ export type BarrelCache = Map<string, Map<string, Target> | undefined>;
7
+
8
+ type Target = { file: string; name: string };
9
+
10
+ const SCRIPT = /(<script\b[^>]*>)([\s\S]*?)(<\/script>)/g;
11
+ // `import { a, b as c } from "lib"`, or `import A from "lib"`.
12
+ const IMPORT =
13
+ /^([ \t]*)import\s+(?:\{([^}]*)\}|([A-Za-z_$][\w$]*))\s*from\s*(["'])([^"']+)\4;?/gm;
14
+ const REEXPORT = /^export\s*\{([^}]*)\}\s*from\s*(["'])(\.{1,2}\/[^"']+)\2$/;
15
+ const COMMENT = /\/\*[\s\S]*?\*\/|\/\/[^\n]*/g;
16
+ const BARE = /^[@a-z]/;
17
+ const ALIAS = /\s+as\s+/;
18
+
19
+ function specifiers(list: string): { name: string; local: string }[] {
20
+ return list
21
+ .split(",")
22
+ .map((part) => part.trim())
23
+ .filter(Boolean)
24
+ .map((part) => {
25
+ const [name = "", local = name] = part.split(ALIAS);
26
+ return { name, local };
27
+ });
28
+ }
29
+
30
+ function readBarrel(file: string): Map<string, Target> | undefined {
31
+ if (!existsSync(file)) return undefined;
32
+ const statements = readFileSync(file, "utf8")
33
+ .replace(COMMENT, "")
34
+ // A statement may span lines: `export {\n a,\n} from "./a.js"`.
35
+ .split(/;|\n(?=\s*(?:export|import)\b)/)
36
+ .map((statement) => statement.trim())
37
+ .filter(Boolean);
38
+ const targets = new Map<string, Target>();
39
+ for (const statement of statements) {
40
+ const reexport = REEXPORT.exec(statement);
41
+ if (!reexport) return undefined;
42
+ const target = join(dirname(file), reexport[3] ?? "");
43
+ for (const { name, local } of specifiers(reexport[1] ?? "")) {
44
+ if (name.startsWith("type ")) continue;
45
+ targets.set(local, { file: target, name });
46
+ }
47
+ }
48
+ return targets;
49
+ }
50
+
51
+ function rewriteImport(
52
+ statement: string,
53
+ indent: string,
54
+ imports: { name: string; local: string }[],
55
+ barrel: Map<string, Target>,
56
+ ): string {
57
+ if (imports.some(({ name }) => name.startsWith("type "))) return statement;
58
+ const lines = [];
59
+ for (const { name, local } of imports) {
60
+ const target = barrel.get(name);
61
+ if (!target) return statement;
62
+ const from = JSON.stringify(target.file);
63
+ lines.push(
64
+ target.name === "default"
65
+ ? `${indent}import ${local} from ${from};`
66
+ : `${indent}import { ${target.name} as ${local} } from ${from};`,
67
+ );
68
+ }
69
+ return lines.join("\n");
70
+ }
71
+
72
+ // compat: Bun drops a barrel's unused components but keeps their CSS
73
+ // imports, so a component imports what it uses from the files a barrel
74
+ // that only re-exports points at.
75
+ export function rewriteBarrelImports(
76
+ source: string,
77
+ importer: string,
78
+ resolveEntry: (specifier: string, importer: string) => string | undefined,
79
+ cache: BarrelCache,
80
+ ): string {
81
+ return source.replace(
82
+ SCRIPT,
83
+ (_block, open: string, code: string, close: string) => {
84
+ const rewritten = code.replace(
85
+ IMPORT,
86
+ (
87
+ statement,
88
+ indent: string,
89
+ list: string | undefined,
90
+ defaultName: string | undefined,
91
+ _quote,
92
+ specifier: string,
93
+ ) => {
94
+ if (!BARE.test(specifier)) return statement;
95
+ const entry = resolveEntry(specifier, importer);
96
+ if (entry === undefined || !entry.includes("node_modules")) {
97
+ return statement;
98
+ }
99
+ if (!cache.has(entry)) cache.set(entry, readBarrel(entry));
100
+ const barrel = cache.get(entry);
101
+ const imports = defaultName
102
+ ? [{ name: "default", local: defaultName }]
103
+ : specifiers(list ?? "");
104
+ return barrel
105
+ ? rewriteImport(statement, indent, imports, barrel)
106
+ : statement;
107
+ },
108
+ );
109
+ return `${open}${rewritten}${close}`;
110
+ },
111
+ );
112
+ }
package/src/index.ts CHANGED
@@ -3,6 +3,7 @@ import { basename, dirname, join, resolve } from "node:path";
3
3
 
4
4
  import type { BunPlugin, OnLoadArgs } from "bun";
5
5
 
6
+ import { type BarrelCache, rewriteBarrelImports } from "./barrel.ts";
6
7
  import { compileFile, type Side, type SvelteCompiler } from "./component.ts";
7
8
  import { productionByEnv, warn, workingDirectory } from "./env.ts";
8
9
  import { SvelteBunError } from "./errors.ts";
@@ -200,6 +201,7 @@ export function svelte(options: SvelteBunOptions = {}): BunPlugin {
200
201
  const onwarn = options.onwarn ?? printWarning;
201
202
  const stylesheets = new Map<string, { css: string; from: string }>();
202
203
  const exportsCache: ExportsCache = new Map();
204
+ const barrelCache: BarrelCache = new Map();
203
205
  // Read on first use, not when the module loads: importing `svelte` from
204
206
  // svelte-bun creates the default export too.
205
207
  let setup: Setup | undefined;
@@ -223,9 +225,38 @@ export function svelte(options: SvelteBunOptions = {}): BunPlugin {
223
225
  return setup;
224
226
  };
225
227
 
228
+ const resolveEntry = (specifier: string, importer: string) => {
229
+ const viaCondition = resolveCondition(
230
+ specifier,
231
+ importer,
232
+ ready().conditions,
233
+ exportsCache,
234
+ );
235
+ if (viaCondition !== undefined) return viaCondition;
236
+ try {
237
+ return Bun.resolveSync(specifier, dirname(importer));
238
+ } catch {
239
+ return undefined;
240
+ }
241
+ };
242
+
226
243
  return {
227
244
  name: "svelte-bun",
228
245
  setup(build) {
246
+ // compat: Bun runs a build's macros, and leaves
247
+ // process.env.NODE_ENV in its output, as development unless the
248
+ // build defines it. Bun.plugin() at runtime has no config, though
249
+ // the type says it does.
250
+ const config: { define?: Record<string, string> } | undefined =
251
+ build.config;
252
+ const define = config?.define ?? {};
253
+ if (config && production && !("process.env.NODE_ENV" in define)) {
254
+ config.define = {
255
+ ...define,
256
+ "process.env.NODE_ENV": JSON.stringify("production"),
257
+ };
258
+ }
259
+
229
260
  build.onResolve({ filter: BARE }, (args) => {
230
261
  const path = resolveCondition(
231
262
  args.path,
@@ -251,6 +282,14 @@ export function svelte(options: SvelteBunOptions = {}): BunPlugin {
251
282
  await compiler.preprocess(source, preprocess, { filename })
252
283
  ).code;
253
284
  }
285
+ if (args.path.endsWith(".svelte")) {
286
+ source = rewriteBarrelImports(
287
+ source,
288
+ args.path,
289
+ resolveEntry,
290
+ barrelCache,
291
+ );
292
+ }
254
293
  out = compileFile(compiler, source, {
255
294
  filename: args.path,
256
295
  side,