feat: improve the error message of expand (#11141)

* feat: improve the error message of `expand`

* Update packages/vite/src/node/env.ts

Co-authored-by: Ben McCann <322311+benmccann@users.noreply.github.com>

Co-authored-by: Ben McCann <322311+benmccann@users.noreply.github.com>
Co-authored-by: sapphi-red <green@sapphi.red>
This commit is contained in:
Dunqing 2022-12-06 14:28:31 +08:00 committed by GitHub
parent 51ceb4ee5c
commit 825c7939ef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -35,15 +35,29 @@ export function loadEnv(
}),
)
// let environment variables use each other
const expandParsed = expand({
const expandOptions = {
parsed: {
...(process.env as any),
...parsed,
},
// prevent process.env mutation
ignoreProcessEnv: true,
}).parsed!
}
let expandParsed: NonNullable<ReturnType<typeof expand>['parsed']>
try {
// let environment variables use each other
expandParsed = expand(expandOptions).parsed!
} catch (e) {
// custom error handling until https://github.com/motdotla/dotenv-expand/issues/65 is fixed upstream
// check for message "TypeError: Cannot read properties of undefined (reading 'split')"
if (e.message.includes('split')) {
throw new Error(
'dotenv-expand failed to expand env vars. Maybe you need to escape `$`?',
)
}
throw e
}
Object.keys(parsed).forEach((key) => {
parsed[key] = expandParsed[key]