【问题标题】:Make Global Objects in Grunt在 Grunt 中创建全局对象
【发布时间】:2016-05-30 06:02:16
【问题描述】:

我正在尝试将 includereplace 插件用于 grunt。我正在尝试通过使用以下代码获取 JSON 来为 globals 属性赋值:

grunt.registerTask('fetchProperties', 'Fetches the properties.json file', function() {
    properties = grunt.file.readJSON('properties.json');
    grunt.log.writeln(['Properties file loaded']);
});

现在当我执行properties.var_a 时,它会正确返回var_a 的值。 所以,我这样做了:

 grunt.registerTask('fetchProperties', 'Fetches the properties.json file', function() {
    properties = grunt.file.readJSON('properties.json');
    grunt.task.run('includereplace');
})

这是我的 includereplace 任务:

includereplace: {
        dist: {
            options: {
                globals: {
                    VAR_A: properties.var_a, 
                    VAR_B: properties.var_b
                },
            },
            files: [{
                src: '../myFiles/path/to/some/file/main.txt',
                dest: '../myOtherFiles/path/to/some/file/mainrep.txt'
            }]
        }
    }

现在被includereplace 任务替换的值是undefined。 如何缓解这个问题? 另外,我尝试使用grunt.config 设置变量,但问题是,我有一个 JSON 文件,加载时将返回一个对象而不是单个值。如何设置一个全局对象,所有任务在执行时都可以使用它来设置它们的参数? 我在 grunt 文件的开头加载 JSON 文件。这是我module.exports = function(grunt) { ... 中的第一行

【问题讨论】:

    标签: javascript json node.js gruntjs


    【解决方案1】:

    成功了!

    grunt.initConfig({
        properties: grunt.file.readJSON('properties.json'),
        includereplace: {
        dist: {
            options: {
                globals: {
                    VAR_A: '<%= properties.var_a %>', 
                    VAR_B: '<%= properties.var_b %>'
                },
            },
            files: [{
                src: '../myFiles/path/to/some/file/main.txt',
                dest: '../myOtherFiles/path/to/some/file/mainrep.txt'
            }]
        }
      }
    });
    

    为此使用了https://stackoverflow.com/a/16792592/2459789

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 2015-03-22
      • 1970-01-01
      • 2018-09-22
      相关资源
      最近更新 更多