rtsao / csjs

:sparkles: Modular, scoped CSS with ES6
MIT License
576 stars 32 forks source link

Helper method for getting true string class names #62

Open rtsao opened 7 years ago

rtsao commented 7 years ago

The .toString() technique employed by csjs can be problematic when used in conjunction with React.PropTypes.string.

Rather than requiring string coercion on behalf of the user, a helper method to return an object of true strings may be convenient.

Context: https://github.com/rtsao/csjs/issues/56

scott113341 commented 7 years ago

How about something like this?

const assert = require('assert');
const csjs = require('csjs');

const styles = csjs`
  .yolo { color: red; }
  .swag { color: blue; }
`.classNames();

assert(styles.yolo === 'yolo_1VebKB');
assert(styles.swag === 'swag_1VebKB');

assert(typeof styles.yolo === 'string');
assert(typeof styles.swag === 'string');

This would come with the disadvantage that all of the Composition information is lost in the case of extends:

const assert = require('assert');
const csjs = require('csjs');

const styles1 = csjs`
  .yolo { color: red; }
`.classNames();

const styles2 = csjs`
  .beans extends ${styles1.yolo} { border: 0; }
`;

// .beans doesn't extend from .yolo
assert(styles2.beans.classNames.length === 1);
assert(styles2.beans.classNames[0]=== 'beans_gdwuK');

This could potentially be remedied by checking if string arguments to the csjs template literal match up with existing scoped classes. However, this is hacky and would probably require namespacing on scoped class names, ie beans_gdwuK becomes __csjs__beans_gdwuK.