grunt.js配置中常见配置选项的继承

时间:2012-11-19 16:48:34

标签: javascript node.js gruntjs

人们如何处理Grunt中针对多个项目的常见配置选项。这些项目将共享一些常见的配置选项,例如:对于min,但每个项目还有私有自定义配置设置,例如只有三分之一的项目需要less或者有不同的选项。

有没有办法在项目之间共享这种通用配置,使用继承或导入现有文件,还是每个项目都必须定义所有设置?

我所指的项目将驻留在目录层次结构中,如

root
    module1
         grunt.js
    module2
         grunt.js
    module3
         grunt.js

是否有某种方法可以在root级别提供常用配置设置?

1 个答案:

答案 0 :(得分:10)

您可以根据需要轻松地将配置存储在尽可能多的外部JSON文件中。 grunt.file.readJSON会在这里帮到你。例如:

module.exports = function(grunt) {

  var concatConf = grunt.file.readJSON('../concat-common.json'),
      minConf = grunt.file.readJSON('../min-common.json');

  // do whatever you want with concatConf and minConf here
  // ...

  // Project configuration.
  grunt.initConfig({
    pkg: '<json:grunt-sample.jquery.json>',
    meta: {
      banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
        '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
        '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +
        '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
        ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
    },

    concat: concatConf,
    min: minConf

    // ...
  });

  // Default task.
  grunt.registerTask('default', 'concat min');

};

不要忘记gruntfile是在Node环境中执行的常规JavaScript文件,配置选项是常规JavaScript对象:)