在没有 grunt.initConfig() 的情况下注册 Grunt 任务

Register Grunt tasks without grunt.initConfig()

我希望我的 gruntfile.js 结构自然,以便微任务一个接一个地执行。 假设我有以下结构:

grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    clean: {
        movedTyping: 'options...'
    },
    copy: {
        typing: 'options...',
        lessVariables: 'options...',
        html: 'options...'
    },
    less: {
        compile: 'options...'
    },
    typescript: {
        compile: 'options...'
    }
});


grunt.registerTask('build', [
    // TYPESCRIPT
    'typescript:compileSingle',
    'copy:typing',
    'clean:movedTyping',

    // LESS
    'less:compile',
    'copy:lessVariables',

    // HTML
    'copy:html'
]);

但我想实现其他结构:

grunt.registerTask('build', function () {
    // TYPESCRIPT
    grunt.task.run('typescript', 'options...');
    grunt.task.run('copy', 'options...');
    grunt.task.run('clean', 'options...');

    // LESS
    grunt.task.run('less', 'options...');
    grunt.task.run('copy', 'options...');

    // HTML
    grunt.task.run('copy', 'options...');
});

怎么办?

您可以使用 设置对象的属性。 (点)符号。所以也可以设置嵌套结构数据。我还没有遇到更简洁的方法,很高兴看到更好的方法。

grunt.registerTask('build', function () {
   // TYPESCRIPT
   grunt.config.set('typescript.compile','<options>');
   grunt.task.run('typescript');

   ......................
});

为了实现这一点,我创建了 NPM 模块 create-grunt-tasks。 现在我的 grunt 文件看起来像这样:

// Gruntfile.js 
module.exports = function (grunt) {
    require('create-grunt-tasks')(grunt, function (create) {
        create.task('build')
            // Compile TypeScript and move typing 
            .sub('typescript', {
                src: 'src/index.ts',
                dest: 'build/index.js',
                options: { module: 'amd', target: 'es5', declaration: true }
            })
            .sub('copy', {
                expand: true, flatten: true,
                src: 'build/index.d.ts',
                dest: 'build/typing/index.d.ts'
            })
            .sub('clean', ['build/index.d.ts'])
            // Copy HTML 
            .sub('copy', {
                expand: true, flatten: true,
                src: 'src/index.html',
                dest: 'build/index.html'
            });
    });
}