alexei/sprintf.js

Feature Request - ES6 class support

borela opened this issue · 6 comments

ES6 classes are called as functions which throws an error; The current workaround is to pass the class enveloped into a function () => MyClass.

Not sure I understand. Can you please provide some sample code and the actual vs. desired outcome?

let sprintfJs = require('sprintf-js').sprintf

class SomeAwesomeClass {
  someMethod() {}
  someMethod2() {}
}

sprintfJs('test %s', () => SomeAwesomeClass)

You can access the snippet here.

First issue
Without the () =>, it tries to invoke the class as if it were a function, so you get the error TypeError: Class constructor SomeAwesomeClass cannot be invoked without 'new'.

Second issue
After using () => to work around the first problem, it converts the class to string which renders the class body instead of only the name, the result of the previous code is:

test class SomeAwesomeClass {\n … someMethod2() {}\n\n }

This can get worse if you use babel plugins which transforms classes to functions. It needs to recognize that a class was passed and render a simplified string, for example:

test [class SomeAwesomeClass]

A use case for this feature would be test suites using https://github.com/mattphillips/jest-each where some times you can put classes in the dataset.

@alexei Added a pull #158 which implements the feature.

Use Class.name or instance.constructor.name

I kind of sort of understand what you're asking. It's that you need a string representation of a class. There are two issues: one is I'm not aware of any standard/convention in that regard. The other, which might be solvable, is that sprintf supports computed values, and JS classes are functions