且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何根据获取的环境变量动态设置 AngularjJS 基本 URL?

更新时间:2022-02-26 00:10:26

我个人用 grunt 做这种事情.

I personnaly do this kind of stuff with grunt.

当我运行我的 angular-app 时,我有多个任务:

When I run my angular-app I have multiple tasks :

> grunt run --target=dev
> grunt run --target=prod
> grunt build --target=dev
> grunt build --target=prod
> etc...

然后 grunt 在 grunt-preprocess 模块的帮助下进行字符串替换:

Then grunt do strings replacement with the help of the grunt-preprocess module :

我的 constants.tpl.js 文件被解析:

[...]
baseUrl:           '/* @echo ENV_WS_URL */',
[...]

并填充了 url.

有无限可能(字符串替换、文件复制等).

There are endless possibilities (string replacements, file copy, etc).

例如使用 grunt 确保开发配置文件不会投入生产..

Doing it with grunt ensure that dev config files do not go in production for example..

如果您感兴趣,我可以提供更多详细信息,但我只想向您展示一种不同的方法.

I can put more details if you're interested but I only wanted to show you a different approach.

编辑 gruntFile 示例:

edit gruntFile example :

'use strict';

module.exports = function(grunt) {

    /**
     * Retrieving current target
     */
    var target = grunt.option('target') || 'dev';
    var availableTargets = [
        'dev',
        'prod'
    ];

    /**
     * Load environment-specific variables
     */
    var envConfig = grunt.file.readJSON('conf.' + target + '.json');

    /**
     * This is the configuration object Grunt uses to give each plugin its
     * instructions.
     */
    grunt.initConfig({
        env: envConfig,       

        /*****************************************/
        /* Build files to a specific env or mode */
        /*****************************************/
        preprocess: {
            options: {
                context: {
                    ENV_WS_URL: '<%= env.wsUrl %>'
                }
            },
            constants: {
                src: 'constants.tpl.js',
                dest: 'constants.js'
            }
        },

        karma: {
            unit: {
                configFile: '<%= src.karma %>',
                autoWatch: false,
                singleRun: true
            },
            watch: {
                configFile: '<%= src.karma %>',
                autoWatch: true,
                singleRun: false
            }
        }

    });


    /****************/
    /* Plugins load */
    /****************/
    grunt.loadNpmTasks('grunt-preprocess');

    /*******************/
    /* Available tasks */
    /*******************/
    grunt.registerTask('run', 'Run task, launch web server for dev part', ['preprocess:constants']);

};

现在,命令:

> grunt run --target=dev

将创建一个带有 url 的新文件

will create a new file with an url