Sveltekit Different Builds

115 Views Asked by At

I need different builds for my sveltekit app. I would like to do something like

npm run build --option1
npm run build --option2

For option1, I want the following vite.config.js

import { defineConfig } from "vite";
import { svelte } from "@sveltejs/vite-plugin-svelte";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [svelte()],
  build: {
    minify: false,
    outDir: "../inst/www",
    sourcemap: true,
    emptyOutDir: true,
  },
  //base: "",
});

and for option 2:

import { defineConfig } from "vite";
import { svelte } from "@sveltejs/vite-plugin-svelte";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [svelte()],
  build: {
    minify: true,
    outDir: "../inst/www",
    sourcemap: false,
    emptyOutDir: true,
  },
  //base: "",
});

Thus, minify: true and sourcemap: false. I was looking for solutions and found a couple but they all seemed rather overcomplicated for such a simple task. So, I am looking for advice of how to best achieve this.

1

There are 1 best solutions below

2
On BEST ANSWER

If you really want to use plain arguments you have to jump through a few hoops. Any arguments are first passed to npm, to prevent that you would need to add --. Then the arguments end up being sent to vite, which does not know option1 and would crash, so you need another -- separator.

So using

npm run build -- -- --option1

would just set an additional argument which you then could read from process.argv in the vite.config.json and conditionally change the config.

If you just want to switch out the entire config, you could just define two different build scripts that set the appropriate Vite flags in package.json:

"scripts": {
    "build:option1": "vite build -c vite.option1.config.js",
    "build:option2": "vite build -c vite.option2.config.js",
    ...

Which then would be executed via

npm run build:option1
npm run build:option2

(You could also combine adding scripts with the first option, of course.)

Aside from that there is also the environment variable option. You could set them with/before the npm run and then access the variables in the config via process.env. Again, setting the variable could be extracted to named scripts but how this is done is platform dependent (there are helpers like cross-env to get around that issue).

cross-env example:

"scripts": {
    "build:option1": "cross-env BUILD_OPTION=1 vite build",
    "build:option2": "cross-env BUILD_OPTION=2 vite build"
    ...