Repository navigation
Expand file tree
/
Copy pathvite.config.js
More file actions
250 lines (232 loc) · 8.32 KB
/
Copy pathvite.config.js
File metadata and controls
250 lines (232 loc) · 8.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import { defineConfig, loadEnv, searchForWorkspaceRoot } from "vite";
import vue from "@vitejs/plugin-vue";
import { fileURLToPath, pathToFileURL, URL } from "node:url";
import { accessSync, readFileSync } from "fs";
import { resolve } from "node:path";
import { nodePolyfills } from "vite-plugin-node-polyfills";
import Icons from "unplugin-icons/vite";
import IconsResolver from "unplugin-icons/resolver";
import Components from "unplugin-vue-components/vite";
import { FileSystemIconLoader } from "unplugin-icons/loaders";
import { BootstrapVueNextResolver } from "bootstrap-vue-next/resolvers";
import { ViteEjsPlugin } from "vite-plugin-ejs";
import { visualizer } from "rollup-plugin-visualizer";
import yargs from "yargs";
// Read JSON files using fs instead of require
const configSchema = JSON.parse(
readFileSync(new URL("./config.schema.json", import.meta.url), "utf-8")
);
const package_ = JSON.parse(
readFileSync(new URL("./package.json", import.meta.url), "utf-8")
);
const isSchemaType = (schema, type) =>
Array.isArray(schema.type) ? schema.type.includes(type) : (schema.type === type);
const optionsForType = (type) =>
Object.entries(configSchema.properties)
.filter(([, schema]) => isSchemaType(schema, type))
.map(([key]) => key);
const defaultConfigPath = fileURLToPath(new URL("./config.js", import.meta.url));
// Parse an array-typed option from a single environment variable value.
// A full JSON array (e.g. '[{"label":"a","url":"b"}]') is used as-is, which
// allows arrays of objects. For convenience, a plain comma-separated list
// (e.g. 'en,de,fr') is also accepted and split into an array of strings.
const parseArrayEnv = (value) => {
const raw = Array.isArray(value) ? value.join(" ") : String(value);
const trimmed = raw.trim();
if (trimmed.startsWith("[")) {
return JSON.parse(trimmed);
}
return trimmed
.split(",")
.map((v) => v.trim())
.filter((v) => v.length > 0);
};
const parseEnvConfig = (rawEnv) => {
const envArgs = Object.entries(rawEnv)
.filter(([key]) => key.startsWith("SB_") && key !== "SB_CONFIG")
.flatMap(([key, value]) => [`--${key.slice(3)}`, value]);
const env = yargs(envArgs)
.parserConfiguration({ "camel-case-expansion": false })
.boolean(optionsForType("boolean"))
.number(optionsForType("number").concat(optionsForType("integer")))
.option(
Object.fromEntries([
...optionsForType("array").map((k) => [k, { coerce: parseArrayEnv }]),
...optionsForType("object").map((k) => [k, { coerce: JSON.parse }]),
])
).argv;
delete env._;
delete env.$0;
return env;
};
const resolveExternalConfigPath = (configFile) => {
if (!configFile) {
return defaultConfigPath;
}
const configPath = resolve(process.cwd(), configFile);
try {
accessSync(configPath);
} catch {
throw new Error(`The config file "${configFile}" could not be found.`);
}
return configPath;
};
export default defineConfig(async ({ mode }) => {
const rawEnv = {
...loadEnv(mode, process.cwd(), ""),
...process.env,
};
const env = parseEnvConfig(rawEnv);
const externalConfigPath = resolveExternalConfigPath(rawEnv.SB_CONFIG);
const defaultConfig = (await import(pathToFileURL(defaultConfigPath).href)).default ?? {};
const externalConfig = (await import(pathToFileURL(externalConfigPath).href)).default ?? {};
const config = Object.assign({}, defaultConfig, externalConfig, env);
const dynamicConfig = ["true", "1", "yes"].includes(
String(rawEnv.DYNAMIC_CONFIG || "").toLowerCase()
);
const configFromEnv = dynamicConfig
? Object.fromEntries(Object.entries(env).filter(([k]) => k !== "pathPrefix"))
: env;
return ({
base: dynamicConfig ? "./" : config.pathPrefix,
build: {
sourcemap: mode !== "minimal",
rollupOptions: {
external: ["fs/promises"],
},
},
css: {
preprocessorOptions: {
scss: {
api: "modern-compiler",
// todo: remove in STAC Browser V6 or if resolved by bootstrap-vue-next.
silenceDeprecations: ["color-functions", "global-builtin", "import", "if-function"],
},
},
},
define: {
STAC_BROWSER_VERSION: JSON.stringify(package_.version),
// JSON.stringify removes e.g. functions from the config,
// but from env we do not accept functions anyway.
CONFIG_FROM_ENV: JSON.stringify(configFromEnv),
// Expose Vue component internals in the e2e build so end-to-end tests can
// reach the OpenLayers map (see tests/e2e/helpers.js). Only enabled when the
// e2e web server sets STAC_BROWSER_E2E; real production builds are unaffected.
__VUE_PROD_DEVTOOLS__: process.env.STAC_BROWSER_E2E === "true",
},
// See https://github.com/vitejs/vite/discussions/14801#discussioncomment-15550931 for details
optimizeDeps: {
include: [
"bootstrap-vue-next/components/*",
"commonmark",
"@radiantearth/stac-fields/*",
"content-type",
"json-source-map",
"stac-node-validator",
"stac-node-validator/src/baseValidator.js",
"@musement/iso-duration"
],
},
plugins: [
vue({
template: {
compilerOptions: {
// Preserve whitespace behavior from Vue 2
whitespace: "preserve",
},
},
}),
ViteEjsPlugin(config),
Components({
dirs: [],
globs: [],
resolvers: [
BootstrapVueNextResolver({
components: {
BContainer: true,
BRow: true,
BCol: true,
BAlert: true,
BButton: true,
BButtonGroup: true,
BBadge: true,
BForm: true,
BFormGroup: true,
BFormInput: true,
BFormInvalidFeedback: true,
BFormSelect: true,
BFormCheckbox: true,
BFormRadio: true,
BFormRadioGroup: true,
BInputGroup: true,
BListGroup: true,
BListGroupItem: true,
BSpinner: true,
},
}), // Auto-register Bootstrap components
IconsResolver({
prefix: false,
enabledCollections: ["bi"],
alias: {
"b-icon": "bi",
},
customCollections: ["share"],
}),
],
}),
Icons({
compiler: "vue3",
customCollections: {
share: FileSystemIconLoader("./src/media/"),
},
}),
nodePolyfills({
include: ["buffer", "path", "process"],
globals: {
Buffer: true,
process: true,
},
}),
mode === "report" &&
visualizer({
filename: "./dist/report.html",
gzipSize: true,
brotliSize: true,
open: true,
}),
],
resolve: {
// Ensure a single instance of OpenLayers (and stac-js) is used even when
// ol-stac is symlinked (npm link) during development. Otherwise ol-stac
// resolves its own copy of `ol`, and adding its LayerGroup to the app's
// Map breaks OpenLayers' internal map wiring (the layer never gets a map).
dedupe: ["ol", "stac-js"],
alias: {
"@": fileURLToPath(new URL("./src", import.meta.url)),
"@stac-browser-external-config": externalConfigPath,
// The e2e tests use their own widgets, see tests/e2e/widgets.config.js
...(process.env.STAC_BROWSER_E2E === "true" ? {
"../../widgets.config": fileURLToPath(new URL("./tests/e2e/widgets.config.js", import.meta.url)),
} : {}),
},
},
server: {
fs: {
allow: [
searchForWorkspaceRoot(process.cwd()),
externalConfigPath
],
},
port: 8080,
// During e2e runs, pre-transform the lazily-imported route views and
// async components on server start. Otherwise the first in-app navigation
// to them (Search view, Sidebar tree, item filter, …) races the cold vite
// transform and can take many seconds under parallel worker load, causing
// intermittent timeouts. Warmup runs in the background and does not delay
// server readiness. Scoped to e2e so normal dev startup is unaffected.
warmup: process.env.STAC_BROWSER_E2E === "true"
? { clientFiles: ["./src/**/*.vue"] }
: undefined,
},
});
});