Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

javascript - Can I have multiple gruntjs files in my project for code organization?

I'm using gruntjs for my project and was wondering if it's possible to have multiple grunt.js files in my project? The reason I'm asking is that my project is organized like so:

grunt.js
|
|- project1
|   |
|   |-grunt.js
|
|- project2
|
|- project3 (etc..)

I want the top level grunt.js to build all the projects. However as the list of projects grow I don't want my top level grunt.js file to become huge. So I would like to organize it so that the top level grunt can call the project level grunt files to build them. Or if someone wants to just build project1, they can go to the project1 folder and run it's own grunt.js. Can this be done? If so, how do I call the other grunt files? If not, then what's an alternative solution other than having one huge grunt.js file? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I recently solved this issue with a very simple solution.
I implemented grunt.config.merge(config) to replace grunt.initConfig(config). You can call it multiple times, and it will simply merge the config into a single config.

Update: As of Grunt v0.4.5, the grunt.config.merge function is built-in, so you no longer need to include it as a separate library.

This allows me to organize my config by feature.
I create a config file for each feature, such as desktop-javascripts.js, desktop-css.js, mobile-javascripts.js, mobile-css.js.
Also, they share common configuration in default-options.js, so I can specify compression settings and what not.

Example

Gruntfile.js:

module.exports = function(grunt) {

  require('./default-options.js')(grunt);
  require('./desktop-javascripts.js')(grunt);
  require('./desktop-css.js')(grunt);
  require('./mobile-javascripts.js')(grunt);
  require('./mobile-css.js')(grunt);

  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-watch');

};

desktop-javascripts.js:

module.exports = function(grunt) {

  // Configure all JavaScript tasks:
  grunt.registerTask('desktop-javascripts', [ 'concat:JS', 'jshint' ]);
  grunt.config.merge({
    concat: { 'JS': { files: allJS } },
    jshint: { 'JS': { files: allJS } },
    watch: { 'JS': { files: allJS, tasks: [ 'desktop-javascripts' ] } }
  });

};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...