Javascript 涉及n个子目录的动态Grunt

Javascript 涉及n个子目录的动态Grunt,javascript,git,gruntjs,Javascript,Git,Gruntjs,我的文件夹布局如下: / -- css/ -- js/ -- apps/ -- -- myFirstApp/ -- -- mySecondApp/ -- -- ... 每一个都是git子模块,都有一个对应的Grunfile、package.json等。我想做的是相同的命令序列,但根据相应的package.json而有所不同 我的命令列表如下: npm install grunt dist copy app/css/[fileName].css (from package.json) to c

我的文件夹布局如下:

/ 
-- css/
-- js/
-- apps/
-- -- myFirstApp/
-- -- mySecondApp/
-- -- ...
每一个都是git子模块,都有一个对应的Grunfile、package.json等。我想做的是相同的命令序列,但根据相应的package.json而有所不同

我的命令列表如下:

npm install
grunt dist
copy app/css/[fileName].css (from package.json) to css/
copy app/js/[fileName].js to js/
copy app/js/[fileName].html to /

有没有一个插件或者我忽略的东西可以和grunt一起使用?如果可能的话,我不想静态地完成它——我只需要更新子模块列表就可以了。

我不知道有任何预构建的Grunt任务可以为您完成这项工作,但是编写任务并不是那么困难。您需要拉入Node
fs
模块来处理文件系统,显然还有其他事情要做。。。下面是它的一般结构,其中包含一些代码和一些
TODO

var fs = require("fs"),
    path = require("path");

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

    ... // all of your other Grunt config

    // options for our new task
    copymodulefiles: {
      all: {
        rootDir: "apps/"
      }
    }

  });

  // Here's our custom task definition
  grunt.registerMultiTask("copymodulefiles", "Copies files from sub-projects", function() {
    var done = this.async(), // tell Grunt this is an async task
        root = grunt.config(this.name + "." + this.target + ".rootDir"),
        modules = fs.readdirSync(root);

    modules.forEach(function(dirName) {
      var pkg = fs.readFileSync(root + dirName + path.sep + "package.json", "utf8");
          pkgJson = JSON.parse(pkg);

      // TODO: find what you need in the pkgJson variable
      //       copy files from wherever to wherever

      // You can write a file like so:
      fs.writeFile(theFilenameToWrite, "Contents of the new file", function (err) {
        // (check for errors!)

        // log it?
        grunt.log.ok("file written!");
      });

    });

    // Determine when all are complete and call "done()" to tell Grunt everything's complete
    // call Grunt's "done" method to signal task completion
    done();

  });
};
我发现它很完美,并且做了类似的任务,比如你正在尝试做的事情

看看我的Gruntfile.js配置,我写了些什么来运行shell命令:

shell: {
        multiple: {
            command: ['bower install',
                      'mv bower_components/** public/',
                  'rm -rf bower_components'
                  ].join('&&')
        }
    }

因此,我在这里运行bower,然后将其组件复制到公用文件夹,然后删除bower\u组件文件夹。因此,我想从这里开始,您可以根据自己的使用情况自定义此脚本

我不确定我是否理解每个子模块的
package.json
会带来什么。。。是不是
[fileName]
?整个目录?我不知道有什么东西可以为父模块的Grunt任务读取子模块的
package.json
文件,但是您可以非常轻松地读取文件系统(使用节点)copy/write files.package.json有一个名为
fileName
的属性,该属性指示生成的js/css/html文件的名称。这是我最初的想法,但我需要访问package.json和其中的一个变量,我无法用
gruntshell
实现这一点。是的,我可以看到您想从
package.json
中读取一些文件名,那么为什么不在
Gruntfile.js
中提及这些内容呢@Seiyraii希望这是完全动态的,这样我就不必每次添加新应用时都添加条目,@NarendraSoni