javascript - 你能在 Grunt 任务中将 Grunt 变量传递给 JavaScript 函数吗?

标签 javascript node.js gruntjs

这是我正在寻找的示例:

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

    config: grunt.file.readYAML('_config.yml'),
    // example variable: <%= config.scripts %>

    copy: {
      scripts: (function() {
        if (config.scripts === true) { // I want to target <%= config.scripts %>
          return {
            expand: true,
            cwd: '<%= input %>/_assets/js/',
            src: '**/*.js',
            dest: '<%= output %>/assets/js/'
          };
        } else {
          return {
            // do nothing
          };
        }
      })()
    }

  });
};

我知道 Grunt 可以使用“grunt.file.readJSON”从文件中读取数据,然后使用以下类型的变量“<%= pkg.value %>”获取该数据。

我想要做的是根据 JSON 文件中的变量创建一个带有 if/else 选项的任务。我不清楚的是如何以它理解的方式将 Grunt 变量 '<%= pkg.value %>' 传递到 JavaScript if 语句中。我试过以与“<%= %>”相同的 Grunt 格式传递它,以及剥离该部分并传递“pkg.value”,但似乎都不起作用。

如果有人能阐明这是否可以完成以及如何完成,我将不胜感激。谢谢!

最佳答案

与其直接在 config 属性中分配 grunt 配置,不如将其存储在变量 (gruntConfig) 中。现在您将能够在以下代码中访问它。

module.exports = function(grunt) {
    // store your grunt config
    var gruntConfig = grunt.file.readYAML('_config.yml');
    // init `script` with an empty object
    var script = {};
    if (gruntConfig.script) {
        script = {
            expand: true,
            cwd: '<%= input %>/_assets/js/',
            src: '**/*.js',
            dest: '<%= output %>/assets/js/'
        };
    }
    // Init Grunt configuration
    grunt.initConfig({
        config: gruntConfig,
        copy: {
            scripts: script
        }
    });
};

关于javascript - 你能在 Grunt 任务中将 Grunt 变量传递给 JavaScript 函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34552042/

相关文章:

javascript - 监控 grunt-contrib-watch 的子任务

javascript - 你能在不使用 Deferred 的情况下写这个吗?

c# - 如何显示 Javascript 警报而不是黄页错误

javascript - Node : what is require modules best practices?

javascript - Node JS - 如何在同一 session 中逐一运行跨浏览器测试?

javascript - 为什么在全局安装时 grunt 不起作用?

javascript - 在 Windows 上运行 Grunt 时出错 : Fatal error: Unable to find local grunt

javascript - 如何在 Jasmine 测试中模拟 Angular $q 服务?

javascript - getSelection.toString() - 不使用 toString()?

javascript - Discord.js();如何发送文件(总是发送0字节文件?)