如何根据相应文件的父文件夹名称使用Grunt重命名文件?

kei*_*rog 50 build-automation rename parent-child gruntjs

我有以下结构:

src/
    modules/
        module1/
            js/
                main.js
            scss/
                main.scss
            index.html
        module2/
            js/
                main.js
            scss/
                main.scss
            index.html
Run Code Online (Sandbox Code Playgroud)

我想运行一个繁琐的任务来将这些复制到以下结构:

dev/
    js/
        module1.js
        module2.js
    css/
        module1.css
        module2.css
    module1.html
    module2.html
Run Code Online (Sandbox Code Playgroud)

有没有办法用现有的grunt插件做到这一点?如果没有,我怎么能实现这个目标?

Glo*_*opy 86

这可以使用grunt-contrib-copy插件完成.

需要注意的主要事项是,您可以使用重命名功能(它接收每个文件的目标和源)以编程方式更改目标.

这是一个(有些脆弱)的样本Gruntfile.js,应该复制到你想要的结构:

module.exports = function(grunt) {
  // Project configuration.
  grunt.initConfig({
    copy: {
      main: {
        files: [
          {
            expand: true, 
            cwd: 'src/modules/', 
            src: ['**/*.js'], 
            dest: 'dev/js/', 
            rename: function(dest, src) {
              // use the source directory to create the file
              // example with your directory structure
              //   dest = 'dev/js/'
              //   src = 'module1/js/main.js'
              return dest + src.substring(0, src.indexOf('/')) + '.js';
            }
          },
          {
            expand: true, 
            cwd: 'src/modules/', 
            src: ['**/*.scss'], 
            dest: 'dev/css/', 
            rename: function(dest, src) {
              return dest + src.substring(0, src.indexOf('/')) + '.css';
            }
          },
          {
            expand: true, 
            cwd: 'src/modules/', 
            src: ['**/*.html'], 
            dest: 'dev/', 
            rename: function(dest, src) {
              return dest + src.substring(0, src.indexOf('/')) + '.html';
            }
          }
        ]
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-copy');

  // Default task(s).
  grunt.registerTask('default', ['copy']);
};
Run Code Online (Sandbox Code Playgroud)

  • 另外非常重要的一点是,如果你想在重命名时跳过某些文件,正确的返回值(默认值)是`return dest +'/'+ src` - 这将导致文件被复制到默认位置. (4认同)

tob*_*bek 5

现在不再需要使用grunt-contrib-copy它了,您现在可以利用grunt.file.expandMapping其中包含更改文件扩展名的选项,或定义返回输出文件名的函数.

以下是将.jade模板编译为.html文件filesjade任务中的对象示例:

files: [{
    expand: true, 
    src: "**/*.jade", 
    dest: "<%= distDir %>", 
    cwd: "<%= assetsDir %>/jade", 
    rename: function(dest, matchedSrcPath, options) {
        // return the destination path and filename:
        return (dest + matchedSrcPath).replace('.jade', '.html');
    }
}]
Run Code Online (Sandbox Code Playgroud)

在这种情况下使用ext: '.html'选项而不是选项会更容易rename,但我在rename这里使用,所以你可以看到它是如何工作的.

有关grunt.file文档中extrename(和其他)选项的更多信息.这里这里有更多的例子.