From 89fe0a9c912cb944e87556ca3cc344c6fac0fc0d Mon Sep 17 00:00:00 2001 From: Day Date: Sat, 23 May 2020 01:27:13 +0800 Subject: [PATCH] feat: support loading customize env variables from .env file (#223) close #213 --- package.json | 1 + playground/.env | 1 + playground/App.vue | 9 ++++----- playground/TestEnv.vue | 24 ++++++++++++++++++++++++ src/node/build/index.ts | 9 ++++++--- src/node/config.ts | 29 +++++++++++++++++++++++------ src/node/server/serverPluginHtml.ts | 9 +++++++-- test/test.js | 8 +++++++- yarn.lock | 5 +++++ 9 files changed, 78 insertions(+), 17 deletions(-) create mode 100644 playground/.env create mode 100644 playground/TestEnv.vue diff --git a/package.json b/package.json index 3f546371324bec..712873253bf433 100644 --- a/package.json +++ b/package.json @@ -67,6 +67,7 @@ "chokidar": "^3.3.1", "cssnano": "^4.1.10", "debug": "^4.1.1", + "dotenv": "^8.2.0", "es-module-lexer": "^0.3.18", "esbuild": "^0.3.2", "etag": "^1.8.1", diff --git a/playground/.env b/playground/.env new file mode 100644 index 00000000000000..ae9a143be28507 --- /dev/null +++ b/playground/.env @@ -0,0 +1 @@ +CUSTOMIZE_ENV_VARIABLE=9527 \ No newline at end of file diff --git a/playground/App.vue b/playground/App.vue index 0495478772f611..34e7f4048cc80a 100644 --- a/playground/App.vue +++ b/playground/App.vue @@ -6,9 +6,7 @@

__BASE__: {{ base }}

-

- process.env.NODE_ENV: {{ env }} -

+

Async Component

@@ -28,6 +26,7 @@ diff --git a/src/node/build/index.ts b/src/node/build/index.ts index 76cf47a98c6fbb..dad327677f5565 100644 --- a/src/node/build/index.ts +++ b/src/node/build/index.ts @@ -159,7 +159,8 @@ export async function build(options: BuildConfig = {}): Promise { minify = true, silent = false, sourcemap = false, - shouldPreload = null + shouldPreload = null, + env = {} } = options let spinner: Ora | undefined @@ -213,8 +214,10 @@ export async function build(options: BuildConfig = {}): Promise { // Vue templates are compiled into js and included in chunks. createReplacePlugin( { - 'process.env.NODE_ENV': '"production"', - 'process.env.': `({}).`, + 'process.env': `(${JSON.stringify({ + ...env, + NODE_ENV: 'production' + })})`, __DEV__: 'false', __BASE__: JSON.stringify(publicBasePath) }, diff --git a/src/node/config.ts b/src/node/config.ts index 96dc8f89bde747..84422675255351 100644 --- a/src/node/config.ts +++ b/src/node/config.ts @@ -1,9 +1,7 @@ import path from 'path' import fs from 'fs-extra' import chalk from 'chalk' -import { createEsbuildPlugin } from './build/buildPluginEsbuild' -import { ServerPlugin } from './server' -import { Resolver } from './resolver' +import { DotenvParseOutput } from 'dotenv' import { Options as RollupPluginVueOptions } from 'rollup-plugin-vue' import { CompilerOptions } from '@vue/compiler-sfc' import Rollup, { @@ -11,6 +9,9 @@ import Rollup, { OutputOptions as RollupOutputOptions, OutputChunk } from 'rollup' +import { createEsbuildPlugin } from './build/buildPluginEsbuild' +import { ServerPlugin } from './server' +import { Resolver } from './resolver' import { Transform } from './transform' import { DepOptimizationOptions } from './depOptimizer' import { IKoaProxiesOptions } from 'koa-proxies' @@ -82,6 +83,10 @@ export interface SharedConfig { factory?: string fragment?: string } + /** + * Environment variables . + */ + env?: DotenvParseOutput } export interface ServerConfig extends SharedConfig { @@ -253,17 +258,18 @@ export async function resolveConfig( configPath: string | undefined ): Promise { const start = Date.now() + const cwd = process.cwd() let config: ResolvedConfig | undefined let resolvedPath: string | undefined let isTS = false if (configPath) { - resolvedPath = path.resolve(process.cwd(), configPath) + resolvedPath = path.resolve(cwd, configPath) } else { - const jsConfigPath = path.resolve(process.cwd(), 'vite.config.js') + const jsConfigPath = path.resolve(cwd, 'vite.config.js') if (fs.existsSync(jsConfigPath)) { resolvedPath = jsConfigPath } else { - const tsConfigPath = path.resolve(process.cwd(), 'vite.config.ts') + const tsConfigPath = path.resolve(cwd, 'vite.config.ts') if (fs.existsSync(tsConfigPath)) { isTS = true resolvedPath = tsConfigPath @@ -326,6 +332,17 @@ export async function resolveConfig( } } + // load environment variables + const envConfigPath = path.resolve(cwd, '.env') + if (fs.existsSync(envConfigPath) && fs.statSync(envConfigPath).isFile()) { + const env = require('dotenv').config() + if (env.error) { + throw env.error + } + + config.env = env.parsed + } + require('debug')('vite:config')( `config resolved in ${Date.now() - start}ms` ) diff --git a/src/node/server/serverPluginHtml.ts b/src/node/server/serverPluginHtml.ts index c418fbbc042d6f..5d58dee5c356e6 100644 --- a/src/node/server/serverPluginHtml.ts +++ b/src/node/server/serverPluginHtml.ts @@ -20,16 +20,21 @@ export const htmlRewritePlugin: ServerPlugin = ({ root, app, watcher, - resolver + resolver, + config }) => { // inject __DEV__ and process.env.NODE_ENV flags // since some ESM builds expect these to be replaced by the bundler + const { env = {} } = config const devInjectionCode = `\n\n` const scriptRE = /(]*>)([\s\S]*?)<\/script>/gm diff --git a/test/test.js b/test/test.js index a713d086852108..607224f39ad757 100644 --- a/test/test.js +++ b/test/test.js @@ -97,9 +97,15 @@ describe('vite', () => { test('env variables', async () => { expect(await getText('.dev')).toMatch(`__DEV__: ${!isBuild}`) expect(await getText('.base')).toMatch(`__BASE__: /`) - expect(await getText('.node_env')).toMatch( + expect(await getText('.node-env')).toMatch( `process.env.NODE_ENV: ${isBuild ? 'production' : 'development'}` ) + expect(await getText('.customize-env-variable')).toMatch( + 'process.env.CUSTOMIZE_ENV_VARIABLE: 9527' + ) + expect(await getText('.defined-variable-names')).toMatch( + 'Defined environment variable names: CUSTOMIZE_ENV_VARIABLE,NODE_ENV' + ) }) test('module resolving', async () => { diff --git a/yarn.lock b/yarn.lock index 07c527548954f5..ab0c48c2886756 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2432,6 +2432,11 @@ dot-prop@^5.2.0: dependencies: is-obj "^2.0.0" +dotenv@^8.2.0: + version "8.2.0" + resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-8.2.0.tgz#97e619259ada750eea3e4ea3e26bceea5424b16a" + integrity sha512-8sJ78ElpbDJBHNeBzUbUVLsqKdccaa/BXF1uPTw3GrvQTBgrQrtObr2mUrE38vzYd8cEv+m/JBfDLioYcfXoaw== + duplexer@0.1.1: version "0.1.1" resolved "https://registry.yarnpkg.com/duplexer/-/duplexer-0.1.1.tgz#ace6ff808c1ce66b57d1ebf97977acb02334cfc1"