【问题标题】:How to access environment variables during build如何在构建期间访问环境变量
【发布时间】:2018-07-26 17:22:02
【问题描述】:

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

例子:

aurelia_project/environments/dev.ts

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

aurelia_project/environments/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/tasks/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));
}

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

【问题讨论】:

    标签: environment-variables aurelia


    【解决方案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));
    }
    

    由于这感觉很老套,我仍然希望有更好的选择!

    【讨论】:

    • 我知道我在 gulp 构建任务中搞砸了导入环境。伙计,这救了我……很高兴你找到了代码!
    猜你喜欢
    • 2017-01-28
    • 1970-01-01
    • 2021-12-22
    • 2021-07-15
    • 2020-11-22
    • 2021-07-28
    • 2018-09-21
    • 1970-01-01
    • 2020-01-05
    相关资源
    最近更新 更多