grunt-esformatter icon indicating copy to clipboard operation
grunt-esformatter copied to clipboard

Add support for `esformatter-jsx` module

Open sedge opened this issue 9 years ago • 4 comments

It would be really nice to have this support. PR incoming...

sedge avatar Apr 03 '15 17:04 sedge

I ran into the same issue and — given the age of this issue — modified the task as follows to support all plugins;

I hope this is of use to someone.

/*
 * grunt-esformatter
 *
 * Copyright (c) 2013 Jörn Zaefferer, contributors
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  grunt.registerMultiTask('esformatter', 'Format JS files', gruntEsformatter);

  function gruntEsformatter() {

    var esformatter = require('esformatter');
    var options = this.options();

    (options.plugins || []).forEach(registerPlugin);

    this.files.forEach(formatFileList);

    function formatFileList(file) {
      file.src
        .filter(assertFile)
        .forEach(formatFile);
    }

    function registerPlugin(name) {
      esformatter.register(require(name));
    }

    function assertFile(filePath) {
      if (grunt.file.exists(filePath)) {
        return true;
      }
      grunt.log.warn('Source file "' + filePath + '" not found.');
      return false;
    }

    function formatFile(file) {

      var formatted;
      var firstLine;
      var content = grunt.file.read(file);

      if (options.skipHashbang) {
        firstLine = content.match(/^#!.+\n/);
        content = content.replace(firstLine, "");
      }

      try {
        formatted = esformatter.format(content, options);
      } catch (e) {
        grunt.log.error('Exception while formatting ' + file);
        grunt.log.error(e.stack);
        return;
      }

      if (options.skipHashbang && firstLine) {
        formatted = firstLine + formatted;
      }

      grunt.file.write(file, formatted);
      grunt.log.writeln('File ' + file + ' formatted.');

    }

  }

};

/cc @jzaefferer @sedge

JamieMason avatar Aug 24 '15 12:08 JamieMason

A pull request would help.

jzaefferer avatar Aug 24 '15 12:08 jzaefferer

Of course, this is ordinarily what I'd do but I held back after seeing this comment from @sedge, that there is work from him to come in this area.

Thanks all.

JamieMason avatar Aug 24 '15 13:08 JamieMason

Good point, I forgot about that PR. Since its been several months, I think you could take this over. Also supporting esformatter plugins in general makes much more sense than supporting one specific plugin.

jzaefferer avatar Aug 24 '15 13:08 jzaefferer