2

我一直在为 grunt 0.3 运行以下任务并移至 0.4,并且 registerHelper 已被弃用。使用新 API 实现此功能的正确方法是什么。

module.exports = function(grunt) {
'use strict';

var fs = require('fs');
var path = require('path');
var crypto = require('crypto');

grunt.registerTask('wpversion', 'Set the versions in scripts.php for CSS/JS', function() {
  var scriptsPhp = 'src/lib/include_functions/scripts.php';

  // Hash the CSS
  var hashCss = grunt.helper('md5', 'dist/assets/css/main.min.css');

  // Hash the JS
  var hashJs = grunt.helper('md5', 'dist/assets/scripts/scripts.min.js');

  // Update scripts.php to reference the new versions
  var regexCss = /(wp_enqueue_style\('main_css',(\s*[^,]+,){2})\s*[^\)]+\);/;
  var regexJs = /(wp_register_script\('main_js',(\s*[^,]+,){2})\s*[^,]+,\s*([^\)]+)\);/;

  var content = grunt.file.read(scriptsPhp);
  content = content.replace(regexCss, "\$1 '" + hashCss + "');");
  content = content.replace(regexJs, "\$1 '" + hashJs + "', " + "\$3);");
  grunt.file.write(scriptsPhp, content);
  grunt.log.writeln('"' + scriptsPhp + '" updated with new CSS/JS versions.');
});

/**
* The 'md5' helper is a basic wrapper around crypto.createHash
*/
grunt.registerHelper('md5', function(filepath) {
  var hash = crypto.createHash('md5');
  hash.update(fs.readFileSync(filepath));
  grunt.log.write('Versioning ' + filepath + '...').ok();
  return hash.digest('hex');
});
};
4

2 回答 2

4

让它成为一个正常的功能。如果它很大,请将其放在一个单独的文件中并要求它。如果它可用于其他任务,请将其发布为节点模块,以便其他任务可以使用它。

于 2013-01-16T14:27:24.563 回答
0

不推荐使用 grunt-helpers,取而代之的是 node 的require. 有一个项目可以帮助使用遗留助手:

https://github.com/gruntjs/grunt-lib-legacyhelpers

于 2013-01-17T19:46:14.900 回答