【问题标题】:Accessing the process / environment from a grunt template从 grunt 模板访问进程/环境
【发布时间】:2012-12-09 00:34:56
【问题描述】:

我在 grunt.js 文件中有一些代码在 0.3 上工作,但在 0.4 上中断:

{
    dest: '<%= process.env.DEST %>/index.html'
}

在 0.3 中定义了进程,因此我可以访问模板内环境中定义的变量,例如将文件路径传递给其他插件。

是否有另一种方法可以在 0.4 中使用?或者在模板渲染时放置一个断点以便我可以看到哪些变量可用?

【问题讨论】:

    标签: javascript templates underscore.js gruntjs


    【解决方案1】:

    The default data is the config object。您可以将环境变量添加到配置对象或直接使用它。

    grunt.initConfig({
        destination: process.env.DEST,
        task: {
            target: {
                dest: '<%= destination %>/index.html'
            }
        },
    });
    

    grunt.initConfig({
        task: {
            target: {
                dest: process.env.DEST + '/index.html'
            }
        },
    });
    

    【讨论】:

    • 感谢您提供非常明确的答案 - 这让我感到困惑!
    • 请注意@SindreSorhus 提到的文档已移至gruntjs.com/api/grunt.config
    【解决方案2】:

    这是 Sindre 的一个很好的直截了当的回答。或者,您可以这样做(使用 grunt-env 插件:https://npmjs.org/package/grunt-env)-

    grunt.initConfig({
        env : {
            test : {
                DEST : 'testDEST'
            },
            dev : {
                DEST : 'devDEST'
            },
            qa : {
                DEST : 'qaDEST'
            },
            prod : {
                DEST : 'prodDEST'
            }
        }
    
    });
    
    
    grunt.registerTask('setenvs', 'Set environment variables', function() {
        grunt.config('ENVS', process.env);
    });
    

    然后使用

    {
        dest: '<%= ENVS.DEST %>/index.html'
    }
    

    你的任务是——

        grunt.registerTask('default', [
            'env:dev',
            'setenvs'
            'yourTask'
        ]);
    

    建议的替代方法只是为了让您可以使用&lt;%= ... %&gt; 而不必在initConfig 中对其进行硬编码。环境目标,您可以将其作为用户的输入并将其传递给环境。

    【讨论】:

    • 是否可以使用 grunt-env 从文件中加载环境变量,对吧?你怎么能访问它们?我目前没有这样做。我想访问一个已经在 webpack 中使用的 .env 文件。可能吗?谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 2015-06-18
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    • 2022-01-04
    相关资源
    最近更新 更多