grunt.initConfig() 전에 비동기 작업을 수행하려면 어떻게 해야 합니까? (How can I perform an asynchronous operation before grunt.initConfig()?)


문제 설명

grunt.initConfig() 전에 비동기 작업을 수행하려면 어떻게 해야 합니까? (How can I perform an asynchronous operation before grunt.initConfig()?)

Now I have my Gruntfile setup to perform some automatic detection magic like parsing sourcefiles to parse some PHP sources in roder to dynamically figure out filenames and paths I need to know before running grunt.initConfig().

Unfortunately grunt.initConfig() doesn't seem to be meant to be run asynchronously, so I see no way to have my asynchronous code executed before I can call it. Is there a trick to accomplish this or do I have to rewrite my detection routines synchronously? Is there any easy way to block execution before my callback has arrived?

Inside grunt tasks there is of course this.async(), but for initConfig() that doesn't work.

Here's a stripped down example:

<pre class="lang‑js prettyprint‑override">function findSomeFilesAndPaths(callback) {
  // async tasks that detect and parse
  // and execute callback(results) when done
}

module.exports = function (grunt) {
  var config = {
    pkg: grunt.file.readJSON('package.json'),
  }

  findSomeFilesAndPaths(function (results) {
    config.watch = {
      coffee: {
        files: results.coffeeDir + "*/.coffee",
        tasks: ["coffee"]
         // ...
      }
    };

    grunt.initConfig(config);

    grunt.loadNpmTasks "grunt‑contrib‑coffee"
    // grunt.loadNpmTasks(...);
  });
};
</code></pre>

Any good ideas how to get this done?

Thanks a lot!


참조 솔루션

방법 1:

I would do it as a task since Grunt is sync or if you can make findSomeFilesAndPaths sync.

grunt.initConfig({
  initData: {},
  watch: {
    coffee: {
      files: ['<%= initData.coffeeDir %>/**/*.coffee'],
      tasks: ['coffee'],
    },
  },
});

grunt.registerTask('init', function() {
  var done = this.async();
  findSomeFilesAndPaths(function(results) {
    // Set our initData in our config
    grunt.config(['initData'], results);
    done();
  });
});

// This is optional but if you want it to
// always run the init task first do this
grunt.renameTask('watch', 'actualWatch');
grunt.registerTask('watch', ['init', 'actualWatch']);

방법 2:

Solved by rewriting, synchronous style. ShellJS came in handy, especially for synchronously executing shell commands.

방법 3:

Example of how you could use ShellJS in Grunt:

grunt.initConfig({
    paths: {
        bootstrap: exec('bundle show bootstrap‑sass').output.replace(/(\r\n|\n|\r)/gm, '')
    },
    uglify: {
        vendor: {
            files: { 'vendor.js': ['<%= paths.bootstrap %>/vendor/assets/javascripts/bootstrap/alert.js']
        }
    }
});

(by leyyinadKyle Robinson Youngleyyinadjgillich)

참조 문서

  1. How can I perform an asynchronous operation before grunt.initConfig()? (CC BY‑SA 3.0/4.0)

#gruntjs #asynchronous #javascript #node.js






관련 질문

프로그램에서 연속적으로 오류 코드를 받는 Gruntfile (Gruntfile getting error codes from programs serially)

grunt.initConfig() 전에 비동기 작업을 수행하려면 어떻게 해야 합니까? (How can I perform an asynchronous operation before grunt.initConfig()?)

grunt 및 qunit을 사용한 로깅 (Logging with grunt and qunit)

Intellij IDEA 13 - 최신 JS 파일을 사용한 아티팩트 빌드 프로세스(grunt 빌드를 통해) (Intellij IDEA 13 - Artifact build process with latest JS files (Via grunt build))

IntelliJ IDEA에서 Grunt 작업에 대한 사용자 지정 config.json 위치 설정 (Setup custom config.json location for Grunt tasks in IntelliJ IDEA)

Grunt 및 Compass와 함께 node-normalize-scss 사용 (Using node-normalize-scss with Grunt and Compass)

npm grunt-libsass 설치 오류 (Error installing npm grunt-libsass)

루트 폴더에 없는 Gruntfile.js가 있는 Visual Studio 작업 실행기 탐색기 (Visual Studio Task Runner Explorer with Gruntfile.js that is not in the root folder)

하위 디렉토리의 Angular2.0, SystemJS는 각도 구성 요소를 가져올 수 없습니다. (Angular2.0 in subdirectory, SystemJS cant import angular components)

html5 모드를 사용하여 Angular 다시 로드 (Reload Angular using html5 mode)

그런트 작업 옵션을 이해하는 방법 (How to understand Grunt task options)

오류: 프로젝트의 기본 XML 네임스페이스는 MSBuild XML 네임스페이스여야 합니다. (Error: The default XML namespace of the project must be the MSBuild XML namespace)







코멘트