diff --git a/packages/core/package.json b/packages/core/package.json index cc9407fa0c..3dbf790cf6 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -74,7 +74,6 @@ "cors": "^2.8.5", "css-loader": "7.1.2", "deepmerge": "^4.3.1", - "dotenv": "16.5.0", "dotenv-expand": "12.0.2", "html-rspack-plugin": "6.1.2", "http-proxy-middleware": "^2.0.9", diff --git a/packages/core/src/loadEnv.ts b/packages/core/src/loadEnv.ts index 736fe7f766..f4c0ab279a 100644 --- a/packages/core/src/loadEnv.ts +++ b/packages/core/src/loadEnv.ts @@ -1,10 +1,60 @@ import fs from 'node:fs'; import { join } from 'node:path'; -import { parse } from 'dotenv'; import { expand } from 'dotenv-expand'; import { color, getNodeEnv, isFileSync } from './helpers'; import { logger } from './logger'; +const DOTENV_LINE = + /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm; + +/** + * This method is modified based on source found in + * https://github.com/motdotla/dotenv/blob/v16.5.0/lib/main.js#L9-L48 + * + * Copyright (c) 2015, Scott Motte + * + * We copied this method because Rsbuild only uses the `parse` method + * in dotenv and most of the other code is redundant. + */ +function parse(src: Buffer) { + const obj: Record = {}; + + // Convert buffer to string + let lines = src.toString(); + + // Convert line breaks to same format + lines = lines.replace(/\r\n?/gm, '\n'); + + let match: RegExpExecArray | null; + // biome-ignore lint/suspicious/noAssignInExpressions: allowed + while ((match = DOTENV_LINE.exec(lines)) != null) { + const key = match[1]; + + // Default undefined or null to empty string + let value = match[2] || ''; + + // Remove whitespace + value = value.trim(); + + // Check if double quoted + const maybeQuote = value[0]; + + // Remove surrounding quotes + value = value.replace(/^(['"`])([\s\S]*)\1$/gm, '$2'); + + // Expand newlines if double quoted + if (maybeQuote === '"') { + value = value.replace(/\\n/g, '\n'); + value = value.replace(/\\r/g, '\r'); + } + + // Add to object + obj[key] = value; + } + + return obj; +} + export type LoadEnvOptions = { /** * The root path to load the env file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9f7fd35a1c..cfb5019249 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -657,9 +657,6 @@ importers: deepmerge: specifier: ^4.3.1 version: 4.3.1 - dotenv: - specifier: 16.5.0 - version: 16.5.0 dotenv-expand: specifier: 12.0.2 version: 12.0.2