【问题标题】:Grunt template variables and if elseGrunt 模板变量和 if else
【发布时间】:2015-05-09 22:08:55
【问题描述】:

我的 Gruntfile 中有一些用于 dist 文件夹的模板变量。我还想在 if else 语句中使用它们来调整一些任务的配置。

这里是我的 Gruntfile 的简短版本:

module.exports = function(grunt) {
    grunt.initConfig({

        // Variables
        path: {
            develop: 'dev/',
            output: 'output/'
        },

        // Clean empty task
        cleanempty: {
            output: {
                src: '<%= path.output %>**/*'
            }
        },

        // Sync
        sync: {
            output: (function(){
                console.log(grunt.config('path.output'));  // Returns undefined

                if(grunt.config('path.output') === 'output/') {
                    return {
                        // Config A
                    }

                } else {
                    return {
                        // Config B
                    }
                }
            }())
        }

不幸的是,我无法让它工作。 grunt.config('path.output') 返回未定义。 如何读取 Grunt 模板变量?更好的解决方案的提示,我也喜欢听。

【问题讨论】:

    标签: javascript variables if-statement gruntjs


    【解决方案1】:

    变量需要在 grunt.initConfig 之外声明。然后你需要在 grunt.initConfig 中引用它

    在以下位置找到我的解决方案: http://chrisawren.com/posts/Advanced-Grunt-tooling

    工作样本:

    module.exports = function(grunt) {
    
        // Variables
        var path = {
            develop: 'dev/',
            output: 'output/'
        };
    
        grunt.initConfig({
            path: path, // <-- Important part, do not forget
    
    
            // Clean empty task
            cleanempty: {
                output: {
                    src: '<%= path.output %>**/*'
                }
            },
    
            // Sync
            sync: {
                output: (function(){
                    console.log(path.output);  // Returns output/
    
                    if(path.output) === 'output/') {
                        return {
                            // Config A
                        }
    
                    } else {
                        return {
                            // Config B
                        }
                    }
                }())
            }
            //...the rest of init config
         });
    
    }
    

    【讨论】:

      【解决方案2】:

      试试

      grunt.config.get('path.output')
      

      【讨论】:

      • 谢谢,但仍然未定义返回。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-04
      • 1970-01-01
      • 2014-03-05
      • 2011-06-26
      • 2010-09-22
      • 2017-10-04
      相关资源
      最近更新 更多