简体   繁体   English

同步grunt.js任务执行

[英]Synchronous grunt.js task execution

I'm trying to extract the critical css for a couple of pages with penthouse via gruntjs. 我正在尝试通过gruntjs提取顶层复数页的关键CSS。 I guess something is wrong, since my debug message gets printed for the whole page array before any of the task actually is being executed. 我猜错了,因为我的调试消息是在实际执行任何任务之前为整个页面数组打印的。 This results in always generating the same file with the same config. 这将导致始终使用相同的配置生成相同的文件。

grunt.registerTask('critical-css',function() {
  grunt.log.writeln( 'Extracting critical css for initial view' );

  var pages = grunt.config('cfg.criticalCss.pages'),
      viewports = grunt.config('cfg.criticalCss.viewports');

  for (var i = pages.length - 1; i >= 0; i--) {

      grunt.log.writeln( 'Processing: ' + pages[i].name );

      for (var a = viewports.length - 1; a >= 0; a--) {

          grunt.config.set( 'ph.server', grunt.config('cfg.criticalCss.server') );
          grunt.config.set( 'ph.urlToAnalyse', pages[i].url );
          grunt.config.set( 'ph.inFile', pages[i].in );
          grunt.config.set( 'ph.outFile', pages[i].out + '-' + viewports[a].name + '.css' );
          grunt.config.set( 'ph.width', viewports[a].width );
          grunt.config.set( 'ph.height', viewports[a].height );

          // run the penthouse task with custom config
          grunt.task.run( 'penthouse' );

      }
  }
});

try changing your var declarations in your for loop to let 尝试在for循环中更改var声明,让

You can use the let keyword to bind variables locally in the scope of for loops. 您可以使用let关键字在for循环范围内在本地绑定变量。 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#let-scoped_variables_in_for_loops -https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/let#let-scoped_variables_in_for_loops

for (let i = pages.length - 1; i >= 0; i--) {

    grunt.log.writeln( 'Processing: ' + pages[i].name );

    for (let a = viewports.length - 1; a >= 0; a--) {

        grunt.config.set( 'ph.server', grunt.config('cfg.criticalCss.server') );
        grunt.config.set( 'ph.urlToAnalyse', pages[i].url );
        grunt.config.set( 'ph.inFile', pages[i].in );
        grunt.config.set( 'ph.outFile', pages[i].out + '-' + viewports[a].name + '.css' );
        grunt.config.set( 'ph.width', viewports[a].width );
        grunt.config.set( 'ph.height', viewports[a].height );

        // run the penthouse task with custom config
        grunt.task.run( 'penthouse' );

    }
}

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

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