Skip to content

Commit

Permalink
fix: support various vite modes of build, not just production (#832)
Browse files Browse the repository at this point in the history
(cherry picked from commit bcc4773fbfc3dd1b7a24655bc731be830ad6d72d)
  • Loading branch information
troyzhxu authored Jun 29, 2021
1 parent cdb10cc commit 95c16a5
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions build/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,22 +39,37 @@ export function wrapperEnv(envConf: Recordable): ViteEnv {
return ret;
}

/**
* 获取当前环境下生效的配置文件名
*/
function getConfFiles() {
const script = process.env.npm_lifecycle_script;
const reg = new RegExp('--mode ([a-z]+) ');
const result = reg.exec(script as string) as any;
if (result) {
const mode = result[1] as string;
return ['.env', `.env.${mode}`];
}
return ['.env', '.env.production'];
}

/**
* Get the environment variables starting with the specified prefix
* @param match prefix
* @param confFiles ext
*/
export function getEnvConfig(match = 'VITE_GLOB_', confFiles = ['.env', '.env.production']) {
export function getEnvConfig(match = 'VITE_GLOB_', confFiles = getConfFiles()) {
let envConfig = {};
confFiles.forEach((item) => {
try {
const env = dotenv.parse(fs.readFileSync(path.resolve(process.cwd(), item)));
envConfig = { ...envConfig, ...env };
} catch (error) {}
} catch (e) {
console.error(`Error in parsing ${item}`, e);
}
});

const reg = new RegExp(`^(${match})`);
Object.keys(envConfig).forEach((key) => {
const reg = new RegExp(`^(${match})`);
if (!reg.test(key)) {
Reflect.deleteProperty(envConfig, key);
}
Expand Down

0 comments on commit 95c16a5

Please sign in to comment.