Skip to content

Allows a vite plugin that runs before SvelteKit travels the routes folder to differentiate multiple vite build #15711

@hgl

Description

@hgl

Describe the problem

My files in the routes folder actually comes from multiple sources (e.g., some are generated from markdown files, and no, I can't use mdsvex due to its limitation).

I'm using a solution similar to what suggested by @Rich-Harris here: #6031 (comment)

The only change is that I wrote a vite plugin to do this pre-processing, so I can use vite's buildtin dev server watcher to watch the source files.

The problem is that SvelteKit runs vite build twice, once for ssr and the other for client, and there is no obvious way to differentiate the two before the vite config gets resolved. This makes my vite plugin run twice. I tried setting a global variable at the plugin's module level to detect the second run. Seem vite always gets run in a new process so this trick doesn't work.

Could SvelteKit set some flag for the second build to make this easier to implement correctly? My plugin implementation is like this

let hasRun = false
export default function vitePluginGenRoutes(): PluginOption {
  return {
    name: "vite-plugin-gen-routes",
    config: {
      order: "pre",
      async handler(config, env): Promise<void> {
        if (hasRun) { // This won't work! hasRun is false even for the second build
          return
        }
        hasRun = true
        generateRoutes()
      },
    },
    configureServer(server): void {
      server.watcher.add([dir]);
    },
  };
}

Describe the proposed solution

The options for the second build is currently pretty generic:

await vite.build({
configFile: vite_config.configFile,
// CLI args
mode: vite_config_env.mode,
logLevel: vite_config.logLevel,
clearScreen: vite_config.clearScreen,
build: {
minify: initial_config.build?.minify,
assetsInlineLimit: vite_config.build.assetsInlineLimit,
sourcemap: vite_config.build.sourcemap
},
optimizeDeps: {
force: vite_config.optimizeDeps.force
}
})
);

Is it possible to set a specific one like build.ssr = false?

I don't know what a good solution could be, this still feels a bit flakey.

Alternatives considered

No response

Importance

would make my life easier

Additional Information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions