如何在构建期间访问环境变量

时间:2017-03-08 21:30:00

标签: environment-variables aurelia aurelia-cli

如何在构建期间访问环境变量的值以进行字符串替换。

示例:

aurelia_project /环境/ dev.ts

export default {
    debug: true,
    testing: true,
    pageBaseUrl: 'https://localhost:9000' // <-- This is the info I'd like to fetch
};

aurelia_project /环境/ prod.ts

export default {
    debug: true,
    testing: true,
    pageBaseUrl: 'https://www.foobar.com' // <-- This is the info I'd like to fetch
};

的index.html

<!DOCTYPE html>
<html>
<head>
    <!-- ... -->
    <base href="{pageBasePath}">
    <!-- ... -->
</head>
<!-- ... -->
</html>

aurelia_project /任务/ processIndex.ts

// ...
export default function processIndex() {
    const pageBasePath = CLI.getEnvParamValue('pageBasePath');

    return gulp.src('index.html')
        .pipe(replace('{pageBasePath}', pageBasePath))
        .pipe(gulp.dest(project.platform.outputIndex));
}

CLI.getEnvParamValue('pageBasePath');中是否有一些内置的虚构processIndex.ts,或者我必须从aurelia_project/environments内的相应文件中手动读取这些信息(使用CLIOptions.getEnvironment() )?

1 个答案:

答案 0 :(得分:1)

我设法通过手动解析相应环境文件中所需的信息来解决这个问题:

let project = require('../aurelia.json');
import * as replace from 'gulp-replace';
import * as gulp from 'gulp';
import {CLIOptions} from 'aurelia-cli';
import * as fs from 'fs';

export default function processIndex() {
    const env = CLIOptions.getEnvironment();
    const envContent = fs.readFileSync(`aurelia_project/environments/${env}.ts`, 'utf8');
    const pageBaseUrl = /pageBaseUrl: '(.*)'/ig.exec(envContent)[1];

    return gulp.src('index.html')
        .pipe(replace('{pageBaseUrl}', pageBaseUrl))
        .pipe(gulp.dest(project.platform.outputIndex));
}

由于这种感觉非常糟糕,我仍然会欣赏更好的选择!