Skip to content

Commit

Permalink
fix(cjs): build cjs for loadEnv (#8305)
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed May 24, 2022
1 parent 9176e27 commit 80dd2df
Show file tree
Hide file tree
Showing 5 changed files with 88 additions and 84 deletions.
2 changes: 1 addition & 1 deletion packages/vite/rollup.config.ts
Expand Up @@ -232,7 +232,7 @@ function createCjsConfig(isProduction: boolean) {
...Object.keys(pkg.dependencies),
...(isProduction ? [] : Object.keys(pkg.devDependencies))
],
plugins: [...createNodePlugins(false, false), bundleSizeLimit(50)]
plugins: [...createNodePlugins(false, false), bundleSizeLimit(55)]
})
}

Expand Down
3 changes: 2 additions & 1 deletion packages/vite/src/node/__tests__/config.spec.ts
@@ -1,7 +1,8 @@
import { describe, expect, test } from 'vitest'
import type { InlineConfig } from '..'
import type { UserConfig, UserConfigExport } from '../config'
import { resolveConfig, resolveEnvPrefix } from '../config'
import { resolveConfig } from '../config'
import { resolveEnvPrefix } from '../env'
import { mergeConfig } from '../publicUtils'

describe('mergeConfig', () => {
Expand Down
84 changes: 2 additions & 82 deletions packages/vite/src/node/config.ts
Expand Up @@ -4,23 +4,20 @@ import { parse as parseUrl, pathToFileURL } from 'url'
import { performance } from 'perf_hooks'
import { createRequire } from 'module'
import colors from 'picocolors'
import dotenv from 'dotenv'
import dotenvExpand from 'dotenv-expand'
import type { Alias, AliasOptions } from 'types/alias'
import { createFilter } from '@rollup/pluginutils'
import aliasPlugin from '@rollup/plugin-alias'
import { build } from 'esbuild'
import type { RollupOptions } from 'rollup'
import type { Plugin } from './plugin'
import type { BuildOptions } from './build'
import type { BuildOptions, ResolvedBuildOptions } from './build'
import { resolveBuildOptions } from './build'
import type { ResolvedServerOptions, ServerOptions } from './server'
import { resolveServerOptions } from './server'
import type { PreviewOptions, ResolvedPreviewOptions } from './preview'
import { resolvePreviewOptions } from './preview'
import type { CSSOptions } from './plugins/css'
import {
arraify,
createDebugger,
dynamicImport,
isExternalUrl,
Expand All @@ -43,7 +40,7 @@ import type { JsonOptions } from './plugins/json'
import type { PluginContainer } from './server/pluginContainer'
import { createPluginContainer } from './server/pluginContainer'
import type { PackageCache } from './packages'
import type { ResolvedBuildOptions } from '.'
import { loadEnv, resolveEnvPrefix } from './env'

const debug = createDebugger('vite:config')

Expand Down Expand Up @@ -858,80 +855,3 @@ async function loadConfigFromBundledFile(
_require.extensions[extension] = defaultLoader
return config
}

export function loadEnv(
mode: string,
envDir: string,
prefixes: string | string[] = 'VITE_'
): Record<string, string> {
if (mode === 'local') {
throw new Error(
`"local" cannot be used as a mode name because it conflicts with ` +
`the .local postfix for .env files.`
)
}
prefixes = arraify(prefixes)
const env: Record<string, string> = {}
const envFiles = [
/** mode local file */ `.env.${mode}.local`,
/** mode file */ `.env.${mode}`,
/** local file */ `.env.local`,
/** default file */ `.env`
]

// check if there are actual env variables starting with VITE_*
// these are typically provided inline and should be prioritized
for (const key in process.env) {
if (
prefixes.some((prefix) => key.startsWith(prefix)) &&
env[key] === undefined
) {
env[key] = process.env[key] as string
}
}

for (const file of envFiles) {
const path = lookupFile(envDir, [file], { pathOnly: true, rootDir: envDir })
if (path) {
const parsed = dotenv.parse(fs.readFileSync(path), {
debug: process.env.DEBUG?.includes('vite:dotenv') || undefined
})

// let environment variables use each other
dotenvExpand({
parsed,
// prevent process.env mutation
ignoreProcessEnv: true
} as any)

// only keys that start with prefix are exposed to client
for (const [key, value] of Object.entries(parsed)) {
if (
prefixes.some((prefix) => key.startsWith(prefix)) &&
env[key] === undefined
) {
env[key] = value
} else if (
key === 'NODE_ENV' &&
process.env.VITE_USER_NODE_ENV === undefined
) {
// NODE_ENV override in .env file
process.env.VITE_USER_NODE_ENV = value
}
}
}
}
return env
}

export function resolveEnvPrefix({
envPrefix = 'VITE_'
}: UserConfig): string[] {
envPrefix = arraify(envPrefix)
if (envPrefix.some((prefix) => prefix === '')) {
throw new Error(
`envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`
)
}
return envPrefix
}
82 changes: 82 additions & 0 deletions packages/vite/src/node/env.ts
@@ -0,0 +1,82 @@
import fs from 'fs'
import dotenv from 'dotenv'
import dotenvExpand from 'dotenv-expand'
import { arraify, lookupFile } from './utils'
import type { UserConfig } from './config'

export function loadEnv(
mode: string,
envDir: string,
prefixes: string | string[] = 'VITE_'
): Record<string, string> {
if (mode === 'local') {
throw new Error(
`"local" cannot be used as a mode name because it conflicts with ` +
`the .local postfix for .env files.`
)
}
prefixes = arraify(prefixes)
const env: Record<string, string> = {}
const envFiles = [
/** mode local file */ `.env.${mode}.local`,
/** mode file */ `.env.${mode}`,
/** local file */ `.env.local`,
/** default file */ `.env`
]

// check if there are actual env variables starting with VITE_*
// these are typically provided inline and should be prioritized
for (const key in process.env) {
if (
prefixes.some((prefix) => key.startsWith(prefix)) &&
env[key] === undefined
) {
env[key] = process.env[key] as string
}
}

for (const file of envFiles) {
const path = lookupFile(envDir, [file], { pathOnly: true, rootDir: envDir })
if (path) {
const parsed = dotenv.parse(fs.readFileSync(path), {
debug: process.env.DEBUG?.includes('vite:dotenv') || undefined
})

// let environment variables use each other
dotenvExpand({
parsed,
// prevent process.env mutation
ignoreProcessEnv: true
} as any)

// only keys that start with prefix are exposed to client
for (const [key, value] of Object.entries(parsed)) {
if (
prefixes.some((prefix) => key.startsWith(prefix)) &&
env[key] === undefined
) {
env[key] = value
} else if (
key === 'NODE_ENV' &&
process.env.VITE_USER_NODE_ENV === undefined
) {
// NODE_ENV override in .env file
process.env.VITE_USER_NODE_ENV = value
}
}
}
}
return env
}

export function resolveEnvPrefix({
envPrefix = 'VITE_'
}: UserConfig): string[] {
envPrefix = arraify(envPrefix)
if (envPrefix.some((prefix) => prefix === '')) {
throw new Error(
`envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`
)
}
return envPrefix
}
1 change: 1 addition & 0 deletions packages/vite/src/node/publicUtils.ts
Expand Up @@ -11,3 +11,4 @@ export { normalizePath, mergeConfig, mergeAlias } from './utils'
export { send } from './server/send'
export { createLogger } from './logger'
export { searchForWorkspaceRoot } from './server/searchRoot'
export { loadEnv, resolveEnvPrefix } from './env'

0 comments on commit 80dd2df

Please sign in to comment.