Skip to content

Commit 27c4b0e

Browse files
authored
refactor: improve .env parsing (#595)
1 parent 6c348c0 commit 27c4b0e

File tree

4 files changed

+164
-156
lines changed

4 files changed

+164
-156
lines changed

apps/base/package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
"@iconify-json/lucide": "1.2.47",
1616
"@iconify-json/simple-icons": "1.2.38",
1717
"@vercel/speed-insights": "^1.2.0",
18+
"dotenv": "^16.5.0",
19+
"motion-plus-vue": "^1.2.1",
1820
"@nuxt/content": "^3.5.1",
1921
"@nuxt/image": "1.10.0",
2022
"@nuxt/scripts": "0.11.8",

packages/cli/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
"@antfu/ni": "^25.0.0",
4545
"@clack/prompts": "0.11.0",
4646
"c12": "3.0.4",
47+
"dotenv": "^16.5.0",
4748
"citty": "^0.1.6",
4849
"defu": "^6.1.4",
4950
"npm-registry-fetch": "18.0.2",

packages/utils/envfile.ts

Lines changed: 21 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,25 @@
1-
function getEachLines(content: string): string[] {
2-
return content.split('\n').filter((line) => line.trim() !== '') // remove empty lines
3-
}
4-
5-
function removeComments(content: string[]): string[] {
6-
return content.filter((line) => !line.startsWith('#'))
7-
}
8-
9-
function getKeyValue(content: string): { key: string; value: string } {
10-
const [key, value] = content.split(/=(.+)/) // split on the first = and the rest of the line
11-
if (!key || !value) {
12-
throw new Error('Invalid .env')
13-
}
14-
return {
15-
key: key.replace(/[\n\r'"]+/g, ''),
16-
value: value.replace(/[\n\r'"]+/g, ''),
17-
}
18-
}
1+
import { parse } from 'dotenv'
192

203
export function parseEnvFile(content: string, withIndex: boolean = false):
214
{ index?: number; key: string; value: string }[] {
22-
const lines = getEachLines(content)
23-
const filteredLines = removeComments(lines)
24-
return filteredLines.map((line, index) => {
25-
const { key, value } = getKeyValue(line)
26-
if (withIndex) {
27-
return { index, key, value }
28-
}
29-
return { key, value }
30-
})
5+
try {
6+
const parsed = parse(content)
7+
8+
const variables = Object.entries(parsed).map(([key, value], index) => {
9+
const result: { index?: number; key: string; value: string } = {
10+
key,
11+
value: value || ''
12+
}
13+
14+
if (withIndex) {
15+
result.index = index
16+
}
17+
18+
return result
19+
})
20+
21+
return variables
22+
} catch (error) {
23+
throw new Error('Invalid .env file format')
24+
}
3125
}

0 commit comments

Comments
 (0)