FrontendAsset Bundling (Vite)

VI · Frontend

Asset Bundling (Vite)

  • @marmeon/vite
On this page

Introduction

A Marmeon app builds its browser code and its server rendering with Vite. The marmeon() plugin of @marmeon/vite sets Vite up for the app, and React's plugin goes next to it:

vite.config.ts
import { marmeon } from '@marmeon/vite';
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';

export default defineConfig({ plugins: [marmeon(), react()] });

The plugin adds the client entry to index.html, builds the browser's files and the server rendering, serves the app's pages, its language files and its route manifest as virtual modules, and refuses server code in the browser. A new app comes with this file. marmeon dev and marmeon build run Vite for you, so you rarely start it yourself.

Installation

Vite and the plugin are development dependencies. Nothing of them runs on a production server:

pnpm add -D vite@^8 @vitejs/plugin-react
pnpm marmeon add vite

Where marmeon add refuses (yarn, bun, a workspace and the other cases listed there), run pnpm add -D @marmeon/vite@<version of your app> instead of the second line.

Vite is a peer of the plugin, so the plugin runs inside your app's own Vite. The types of the virtual modules come from @marmeon/vite/client in compilerOptions.types of tsconfig.json, which a new app lists. The plugin also makes the app and the framework share one copy of React, which hooks need.

The entries

The plugin looks for two entries:

EntryDefaultWhat it does
Clientbootstrap/client.tsxStarts the app in the browser. The plugin adds it to index.html.
Serverbootstrap/ssr.tsxExports render, which the server calls for every page.

index.html is the document every page renders into. The server puts the page's head where <!--app-head--> stands and its markup where <!--app-html--> stands. Keep both comments, and keep the element with the id app around the markup. The pages page shows what the entries contain.

The dev server

marmeon dev runs Vite inside the app's server, on the app's port. An edited page or layout updates in the browser without a reload, and the server renders the edited page on the next request without a restart. A change to server code restarts the server.

Before you change server in vite.config.ts, know what the app relies on:

  • Host names. Vite answers only the host names it allows, and refuses others with a 403, which protects against DNS rebinding. localhost and IP addresses are allowed. When APP_URL uses another name, such as http://notes.test, add it: server: { allowedHosts: ['notes.test'] }. allowedHosts: true turns the check off, and so does server.https. Use either only on a network you trust, because then any page the browser visits can reach the dev server under a name of its own. The framework's own development routes keep their own check either way.
  • Other origins. The server answers no other origin, so a page on another site cannot read the app's development answers.
  • Files Vite will not serve. Beyond Vite's own list (.env files, keys and certificates, .git), the dev server refuses storage/, dist/ and .marmeon/ of the app root, and every database file (*.sqlite, *.sqlite3, *.db, *.db3 and their -wal/-shm companions), with a 403, even to a client on the network. A page that loads a file from storage/ through Vite stops working: serve it with a route. An entry of your own in server.fs.deny is added to the list. A symlink elsewhere in the app that points into storage/ is still served, so do not create one. Tests and builds are unchanged.
  • Styles and the policy. The stylesheets the client entry imports are linked in development with a <link> to the app's own origin that carries the response's CSP nonce; the <style> elements Vite adds later carry it too. A Content-Security-Policy with styleSrc: ["'self'", NONCE] therefore holds in development too. The styling page explains the policy.

Vite resolves the packages your app uses under the condition @marmeon/source, in development and in tests. A package of your workspace that offers it is served from its src/. Node does not follow Vite here: it needs NODE_OPTIONS=--conditions=@marmeon/source too, as a package in your app's workspace shows. An installed marmeon build and marmeon start never add the condition.

Building

marmeon build runs the type check and both Vite builds, among other steps that the deployment page lists. Vite writes the browser's files to dist/client/ and the server rendering to dist/server/ssr.js.

The first page loads two scripts: vendor, with the npm packages such as React, and index, with the framework, your entry and your layouts. vendor stays cached across your own deployments, as long as the packages do not change. Pages, dialogs and features that load on first use stay in chunks of their own. The client entry starts as soon as it has arrived, so a streamed page hydrates its first part while slower parts still arrive.

In production, each document also names the scripts its page needs, so the browser fetches them with the document instead of after index has run: the page's chunk, the chunks it imports and the one for tab sync, as <link rel="modulepreload"> tags, and the page's stylesheets as <link rel="stylesheet"> tags. The server reads them from dist/client/.vite/manifest.json when it starts. Without that file the documents preload nothing; a file that is no Vite manifest stops the start. Nothing is preloaded in development, and the manifest is never served.

Packages with an entry

When an installed package declares a namespace and an entry (see packages with pages or components), marmeon build still runs one client build and one server build, and each entry is an input of it: index.html for the app, the package's client entry for the package, and dist/server/ssr-<namespace>.js next to ssr.js. Without such a package nothing changes: the same inputs, the same chunks, the same file names.

A document loads only code its own entry imports, through any import. A module only the package's entry reaches never lands in a chunk the app's first page loads, and the other way round, and the stylesheets stay separate. A module that several entries import lies in a chunk shared by exactly those entries, named by a hash of them: React and other npm packages in vendor-shared-*, the framework and your code in shared-*. With more entries, each combination of them has chunks of its own. A page of the app that imports a module of the package loads just that module.

The build also writes dist/client/.vite/marmeon-entries.json (format 1): entries gives each namespace the key of its client entry in manifest.json, pages each <namespace>::<view> the key of its page. Like the manifest, it is read by the server and never served.

The base

The server serves dist/client under /, so Vite's base is / (the default) or an absolute URL where you put the assets yourself, such as base: 'https://cdn.example/app/'. With a URL, index.html, the preload tags and the page stylesheets all start with it. The server reads it from the built index.html. A path such as /static/ or a relative ./ fails marmeon build, because the server would answer every asset with a 404; a build made earlier stops marmeon start with a message that names the value. Every tag is crossorigin, so the CDN must answer scripts, stylesheets and fonts with Access-Control-Allow-Origin. Under the default policy ('nonce-…' 'strict-dynamic') the nonce admits the scripts and, with the strict recipe, the stylesheets; a policy without the nonce needs the origin in script-src and style-src.

Every script, stylesheet and preload tag of index.html gets a nonce placeholder. The server puts each response's nonce in its place, or removes the attribute when the response has no policy.

Fonts

A web font starts to load only when the browser has parsed the stylesheet that names it, so text paints late or swaps. fonts names the files the first screen sets, and marmeon build adds a <link rel="preload" as="font" crossorigin> for each to the built index.html:

vite.config.ts
export default defineConfig({
  plugins: [
    marmeon({ fonts: [{ file: '@fontsource-variable/ibm-plex-sans/files/ibm-plex-sans-latin-wght-normal.woff2' }] }),
    react(),
  ],
});

The stylesheet still declares the font, for example with @import '@fontsource-variable/ibm-plex-sans/wght.css'. file is the path inside the package, and only .woff2 is accepted: every browser that preloads fonts reads it, and a .ttf or .woff would be a second download. The URL in the tag is the file's hashed one under /assets/, so it caches for good. The option never becomes a URL by itself.

Name only what the first screen sets, since a preloaded file competes with the styles and scripts for the first bytes. A font package ships many subsets and weights, and the manifest cannot tell which ones your pages use, so the plugin does not guess. More than four files log a warning. A named font is never inlined into the stylesheet, whatever its size. A file that the build does not emit, because the name is wrong or no stylesheet loads it, stops the build with its name. A file that is not a .woff2 path of a package stops the config. Nothing is preloaded in development, where the dev server loads the font with the stylesheet, and test: true checks the entries but adds no preload.

A fallback with the same size

While the font loads, the browser sets the text in the next font of the stack, and when the font arrives the lines move, because every font takes another width and height. With family and fallback, the plugin reads the font's own metrics (head, hhea and OS/2, from the file; no extra package) and writes a fallback that takes the same room:

vite.config.ts
marmeon({
  fonts: [{ file: '@fontsource-variable/ibm-plex-sans/files/ibm-plex-sans-latin-wght-normal.woff2', family: 'IBM Plex Sans Variable', fallback: 'Arial' }],
});

The fallback is a font named <family> Fallback, made from the local font fallback with size-adjust and the three *-override descriptors. Import the stylesheet from the client entry and put the fallback after the font in font-family:

bootstrap/client.tsx
import 'virtual:marmeon/fonts.css';
styles/app.css
body { font-family: 'IBM Plex Sans Variable', 'IBM Plex Sans Variable Fallback', system-ui, sans-serif; }

family is the name the font's own @font-face gives it, with letters, digits, spaces and - only: it is written into CSS, so anything else stops the config. fallback is one of Arial, Helvetica, Times New Roman, Georgia and Courier New; pick the one that looks closest (sans-serif, serif or monospace). Both go together. The font may be .woff2 only, as for the preload; a file the plugin cannot read stops the build with its name. Helvetica exists only on Apple systems, and Arial or Times New Roman are often missing on Linux and Android; there the browser takes the next font of the stack, as it would without a fallback. The stylesheet is bundled with the app's own, so a strict style-src needs nothing, and it works in development the same way. It exists once fonts has an entry.

Virtual modules

The plugin serves these modules for your entries to import:

ModuleWhat it exportsUsed by
virtual:marmeon/pagesEvery page, each loaded on its own, keyed by its pathresolveModulePages(pages)
virtual:marmeon/langEvery language file, each loaded on its owncreateMessageLoader(lang) of @marmeon/i18n/messages
virtual:marmeon/lang/<namespace>The language files of one package with an entry, with the app's lang/<namespace>/ laid over them, each loaded on its own; the app's virtual:marmeon/lang holds none of them (texts of a package)the package's entry, createMessageLoader(lang)
virtual:marmeon/pages/<namespace>The pages of one package with pages, keyed <namespace>::<view>, each loaded on its ownresolveModulePages(pages)
virtual:marmeon/routesroutes: the named routes the browser knowscreateMarmeonApp({ routes }), createSsrRenderer(…, { routes })
virtual:marmeon/fonts.cssThe stylesheet of the fallback fonts, once fonts has an entrythe client entry, import 'virtual:marmeon/fonts.css' (fonts)
virtual:marmeon/test-packagesNothing: importing it makes the packages of your workspace load once in your tests, and only with test: true (packages of your workspace)the setup file of a test project
bootstrap/pages.ts
import { resolveModulePages } from '@marmeon/react';
import pages from 'virtual:marmeon/pages';

export const resolvePage = resolveModulePages(pages);

Vite keeps them current when you add or remove a page or a language file. The browser loads only the language files of the page's locale. The route manifest holds only the routes your client code names. The URL generation page explains which those are.

Packages with pages or components

A package that declares a namespace in the "marmeon" field of its package.json is user interface: the plugin has the app's Vite compile it like the app's own source, in development, in marmeon build and in server rendering, so every plugin of the app sees its modules. For each such package the plugin

  • adds the package to ssr.noExternal, so server rendering bundles it and a stylesheet it imports does not reach Node;
  • adds it to optimizeDeps.exclude and its client entry to optimizeDeps.entries, so the dev server serves its modules through the plugin chain instead of pre-bundling them;
  • lets the dev server serve its folder (server.fs.allow: added to your own list, or, when you set none, to the workspace the app lies in; server.fs.deny stays);
  • collects the route names its code writes out (<Link route>, useRoute()), so they reach the browser's route manifest like the app's own. Only declared packages count: the code of any other package in node_modules stays out. A package ships compiled JSX, so the build also reads the compiled form jsx(Link, { route: 'status.index' }) (jsx, jsxs and jsxDEV from react/jsx-runtime or react/jsx-dev-runtime, and createElement from react), with the component imported from @marmeon/react and the props written as an object literal. This needs ES module output: props built by a helper (Object.assign, _objectSpread) or CommonJS require calls are not read, and their route names are missing.

Nothing is scanned: the plugin acts on the packages the app's dependencies declare, resolved from package.json alone. A package with a client entry also gets virtual:marmeon/pages/<namespace>, the same as virtual:marmeon/pages for the pages the package lists under views, keyed <namespace>::<view> (status::entries/Edit). A namespace no package declares, or a package without pages, is an error when the module is imported. The plugin checks each file again when it builds the module, so a file that has turned into a link out of the package is refused.

Put the files that run in the browser (the client entry, the views, the components) under the package's browser globs, and ship them as compiled ESM with finished CSS: the app's Tailwind sees no directive inside it. A package nested in another is found through the app's dependency list, so a transitive package counts as well.

Options

marmeon() works without options. These change its conventions:

OptionDefaultEffect
entries{ client: 'bootstrap/client.tsx', ssr: 'bootstrap/ssr.tsx' }Where the entries are, relative to the app root.
fontsnone.woff2 files to preload from index.html, as { file }, and with family and fallback a fallback font of the same size. See Fonts.
serverModulesnoneMore server modules for this config only, as globs; '!glob' takes files out of the conventions. Declare them in package.json so that tests and the lint preset see them too.
routeSinksnoneMore places where client code hands the framework a route name, for an adapter of your own.
images{ widths: [640, 960, 1280, 1920, 2560], formats: ['avif', 'webp'], quality: 70 }How ?image imports are built. See Images of the app.
testfalseFor vitest.config.ts.
viteEnvfalseKeep Vite's own handling of .env files and VITE_* variables. See Environment variables.

Pages are the .tsx files in modules/<module>/views/, and language files are the .ts files in lang/ and modules/<module>/lang/. marmeon() takes no pages or lang option and throws a TypeError if you pass one.

Environment variables

Vite normally reads the .env files of the app's folder and writes every VITE_* variable that client code reads through import.meta.env into the public bundle, whatever its value. A misnamed variable, or a CI secret that happens to start with VITE_, would reach every visitor without passing the configuration checks.

marmeon() therefore reads no .env file and gives import.meta.env no variable prefix: import.meta.env.VITE_* is undefined, in marmeon dev and in marmeon build. import.meta.env.MODE, DEV, PROD, SSR and BASE_URL stay. This holds in client and in server (SSR) code. To hand a value to the browser, share it as a prop.

The plugin owns envDir and envPrefix: an app's own value, or a prefix another plugin adds, stops the start with an error that names viteEnv: true.

An app that needs Vite's behaviour sets marmeon({ viteEnv: true }) in vite.config.ts, and in vitest.config.ts if its tests read the variables. Then every VITE_* variable of the process and of the .env files is public.

Server code in the browser

A page, a layout, the client entry and every module they import run in the browser. None of them may import a server module as a value, because a value import bundles the module, and everything it imports, into the browser:

import { ShowNoteController } from '../controllers/ShowNoteController.ts';        // refused: ships the controller
import type { ShowNoteController } from '../controllers/ShowNoteController.ts';   // erased: the view needs the type only

A class is a value even where only its type is used. import { type ShowNoteController } is not enough either, because the compiler keeps it as an empty import that still loads the module. The plugin refuses such an import in Vite's overlay while you develop, and the build stops with the file, the line and the fix:

✗ [marmeon] modules/notes/views/Show.tsx:3:1 — imports modules/notes/controllers/ShowNoteController.ts as a value: a controller is server code, and a value import bundles it — with everything it imports — into the browser. A class is a value even where only its type is used: write import type { ShowNoteController } from '../controllers/ShowNoteController.ts'. If the browser needs a value from it, move that value into a module both sides import.
✗ Not built: 1 import brings server code into the browser.

An indirect import counts too. When a page imports a helper that imports a controller, the error names the helper's line and the way from the page to it. Tests check the same: server rendering in tests and Vitest with marmeon({ test: true }).

These files are server modules by convention:

PatternWhat
modules/*/controllers/**Controllers
modules/*/listeners/**, jobs/**, mail/**, notifications/**, policies/**, middleware/**, tasks/**, health/**, commands/**, migrations/**, seeders/**, factories/**Each of its kind, inside a module
modules/*/index.ts, routes.ts, api-routes.ts, schedule.ts, config.tsA module's definition, routes, schedule and configuration
**/*ServiceProvider.ts, **/*Repository.tsService providers and repositories
bootstrap/app.ts, config/**, middleware/**The app's definition, its configuration and its middleware

Anything else becomes client code as soon as a page imports it: views, layouts, language files, a shared.ts. When the browser needs a value from a server module, move the value into a module both sides import. Server folders of your own adds folders of your own.

Two packages count as server modules too: @marmeon/mail and @marmeon/react/mail. A mail is composed on the server, and a value import of either in client code would bundle the mailer and the MJML compiler into the browser; the error says to render it in modules/<module>/mail/. import type from them stays fine.

The check reads the source while building and adds no code to any chunk. The lint preset, which marmeon make:lint-config writes, flags the common case in the editor already. The console page lists the command.

Server folders of your own

A feature folder such as modules/billing/invoices/ or a renamed folder is no convention. Declare it once in the "marmeon" field of the app's package.json:

package.json
{
  "marmeon": {
    "serverModules": ["modules/billing/invoices/**", "!modules/notes/jobs/labels.ts"]
  }
}

marmeon dev, marmeon build and Vitest with marmeon({ test: true }) read the list, so a value import from one of these folders fails in all three without a line in vite.config.ts or vitest.config.ts. Each entry is a glob relative to the app root:

  • !glob takes files out of the conventions and out of the list, such as !modules/notes/jobs/labels.ts.
  • Write a folder as folder/**; a name with no * and no file extension matches no file.
  • No leading /, no \, no . or .. segment, no empty segment, no space at either end and no leading #.
  • No braces, (, ) or |: list each alternative as its own entry. No ? and no […] either: the build and the lint preset would read them differently, so spell the name out or use *.

An entry that does not hold to this, an unreadable package.json or a misspelt key in "marmeon" stops the dev server, the build and the tests with H14. A declaration that is silently skipped would leave a folder unchecked, which is why it is an error. Restart marmeon dev after you change the list.

The lint preset takes the list over when marmeon make:lint-config --force (with --boundaries, if you use it) writes it anew. See lint.

The serverModules option of the plugin adds patterns for one config only. It takes globs too, but they are not checked against these rules, and the lint preset does not see them, so declare folders in package.json.

Tests

vitest.config.ts uses the plugin with test: true:

vitest.config.ts
import { marmeon } from '@marmeon/vite';
import { defineConfig } from 'vitest/config';

export default defineConfig({
  plugins: [marmeon({ test: true })],
  test: { include: ['modules/**/*.test.ts'] },
});

In this mode the plugin sets up module resolution, the container's injection, the virtual modules and the server-import check, and nothing for the browser: no entries, no HTML, no nonce and no build settings.

Resolution includes the condition @marmeon/source, so a test loads the sources of a package in your workspace with no variable. A process a test starts does not.

To share one instance of a package of your workspace between a test and the app it boots, see packages of your workspace.

Packages of your workspace

A package of your own workspace is one that your app links, with workspace: or link:, and that lies outside node_modules. In a test such a package is loaded twice: the app boots it through Node's import(), and your test imports it through Vitest.

The two copies show as a provider that your test imports and the booted app does not list, a token that resolves to nothing (K1), a class without its injection list (K3), a second singleton, or a vi.mock that the booted app never sees.

Import virtual:marmeon/test-packages in a setup file to load these packages once, through Vitest, for the tests and for the app they boot. The import needs marmeon({ test: true }) and Vitest 5.1.1 or newer.

vitest.setup.ts
import 'virtual:marmeon/test-packages';
vitest.config.ts
import { marmeon } from '@marmeon/vite';
import { defineConfig } from 'vitest/config';

export default defineConfig({
  plugins: [marmeon({ test: true })],
  test: { include: ['modules/**/*.test.ts'], setupFiles: ['./vitest.setup.ts'] },
});

With test.projects, give the plugin and the setup file to each project that boots an app. A project without the import, and everything outside tests, loads these packages through Node.

What changes with the import:

  • The provider class your test imports is the one the app boots, and so are its tokens and singletons.
  • A vi.mock of a module of the package reaches the boot, except where one variant per test file says otherwise.
  • A mock of an entry must export what discovery needs: the providers, the classes with constructor dependencies and what they inject. A mock that leaves one out fails the boot with Vitest's error, which names the export. An export that is undefined and a class to inject that is null or a primitive fail it with K7.
  • To change a mock between two boots, use vi.resetModules() with vi.doMock(), and then import the app's definition and the classes again with await import(): what the file imported before the reset keeps the first variant. One variant per test file names the classes that this does not change.
  • Remove server.deps.external entries of these packages if their mocks and resets shall reach the boot.

One variant per test file. Some classes are not evaluated again with what they inject: a class of an installed package that injects a class of your workspace, a class of a package in server.deps.external, and, without a reset, a class of a built package that has no embedded injection lists. With the import, the first boot that discovers such a class decides what is injected into it, for the whole test file and for apps that already run. That boot can be one in a setup file, and a boot that failed counts too. A mock that comes later does not reach the class, and a mock of the first boot stays, also in a boot that stubs production and in an app with discover: false. Put each variant in a test file of its own, with isolate on (the default), and boot in that file rather than in a setup file.

Where the import does not apply, discovery loads the package through Node:

  • DOM environments (happy-dom, jsdom) and browser mode: the import registers nothing and removes a registered importer.
  • Installed packages, below node_modules: a mock of one does not reach discovery's own import of it, and their imports of a workspace package are Node's.
  • A package in server.deps.external: it is one instance, through Node. A mock of its entry reaches the boot. A mock of a module inside it and vi.resetModules() do not, and its imports of a workspace package are Node's.
  • Files that are loaded by URL: migrations, language files and tinker.
  • A boot while the process's NODE_ENV is neither development nor test, for example after vi.stubEnv(): discovery loads the real providers. What your app imports itself stays mocked, and so can an injected class. The env option of createTestApp() reaches the app's configuration and not the process. For a protection that is asked per request, boot first and stub afterwards (which environment a test runs in).

The import refuses:

  • When it loads: a Vitest older than 5.1.1, a prerelease or a version it cannot read (the message has the install command), and resolve.preserveSymlinks: true.
  • At the boot, naming the file: a name with ? or #, a file that Vite resolves to another file or cannot resolve, and one that a plugin resolves as external.
  • With Vitest's native runner (experimental.viteModuleRunner: false) the import cannot load at all: leave it out.

What it does not cover:

  • A package that boots an app while it loads and waits for it: the boot waits for the package, and neither ends.
  • A mock factory that boots an app: that inner boot runs the real module.
  • @marmeon/core run by Vitest itself (server.deps.inline, or linked from a checkout): discovery's own import is then the runner's, so a mock reaches every boot, also one under a production stub.
  • isolate: false and the pools vmThreads and vmForks are not tested.
  • With sequence.setupFiles: 'parallel', import it in the test file that boots the app.

When the plugin is missing

The server reads the entries from the plugin. A vite.config.ts without marmeon() stops marmeon dev and marmeon build:

vite.config.ts does not use the marmeon() plugin, which tells the server where the app's entries are:
  import { marmeon } from '@marmeon/vite';
  export default defineConfig({ plugins: [marmeon(), react()] });