简体   繁体   English

在grunt中不存在时创建文件/文件夹的任务

[英]Task to create files/folders when they don't exist in grunt

I'm trying to automate my testing and was wanting to automatically create test files for any javascript that is created on src folder. 我正在尝试自动化我的测试,并且想要为在src文件夹上创建的任何javascript自动创建测试文件。 Here's a break down on my folder structure. 这是我文件夹结构的细分。

js
--src
  --sum.js
  --subtract.js
  --calculator.js
  --innerFolder
    --multiply.js
    --divide.js
--specs

So from the above folder structure what I want to do is create all the folder structure and files on my specs like this only if the file on the destination folder doesn't already exist :- 所以从上面的文件夹结构我想要做的是只有当目标文件夹上的文件不存在时才在我的规范上创建所有文件夹结构和文件: -

js
--src
  --sum.js
  --subtract.js
  --calculator.js
  --innerFolder
    --multiply.js
    --divide.js
--specs
  --sumSpec.js
  --subtractSpec.js
  --calculator.js
  --innerFolder
    --multiplySpec.js
    --divideSpec.js

My approach to tackle this is by watching all the files/folders on src folder doing :- 我解决这个问题的方法是观察src文件夹中的所有文件/文件夹:

watch:{
  src : {
    files: ['src/**/*.*'],
    tasks:  //create files and folders on specs folders here
}

I came across grunt.file plugin and also have considered grunt-shell and making my own script to achieve this. 我遇到了grunt.file插件,并且还考虑了grunt-shell并制作了自己的脚本来实现这一点。

But I was wondering if there was already an easier way to do this. 但我想知道是否已经有一种更简单的方法来做到这一点。

Try the copy task along with the filter property: 尝试复制任务以及filter属性:

grunt.initConfig({
  copy: {
    js: {
      expand: true,
      cwd: 'js/src',
      src: '**/*.js',
      dest: 'js/specs',
      filter: function(filepath) {
        var path = require('path');
        var dest = path.join(
          grunt.config('copy.js.dest'),
          // Remove the parent 'js/src' from filepath
          filepath.split(path.sep).slice(2).join(path.sep)
        );
        return !(grunt.file.exists(dest));
      },
    },
  },
  watch: {
    js: {
      files: ['js/src/**/*.js'],
      tasks: ['copy:js'],
    },
  },
});

Then you can have it copy files that don't exist as you edit or run grunt copy:js . 然后,您可以复制在编辑或运行grunt copy:js不存在的grunt copy:js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM