Plugin to use custom class name
See original GitHub issueIdea: I want to customize those classes generated by Prism for each token (for example, var
in JS will be generated to <span class="token keyword">var</span>
. I want to change the string “token keyword”.
Reason: Some situation require me to use locally scoped classes, like in a CSS Modules project or one that follow BEM Style.
Solution: I wrote a small plugin, based on Highlight Keyword, to customize those classes using a style-map object. The object looks like this:
var customStyleMap = {
tokenType: className
}
with tokenType
is type of token I want to customize (eg: 'keyword'
, 'string'
, 'operator'
…) and className
is the class string I want to use for that token (eg: 'my-special-class-for-token'
or a hashed one like '_3ka93h'
Example Usage:
var customStyleMap = {
keyword: 'special-keyword',
string: 'special-string'
};
customizePrismClasses(customStyleMap);
Or we can use the object returned by CSS Modules:
var customStyleMap = require('my-custom-style-map.css');
customizePrismClasses(customStyleMap);
Then, the string var
will become <span class="special-keyword">var</span>
.
The source code is very simple, but I think it is useful, especially for project which we want to scope the class name locally, like CSS Modules projects.
Please tell me what do you guys think about this. I’ll make a pull request if you think it is useful enough.
Issue Analytics
- State:
- Created 7 years ago
- Comments:15 (12 by maintainers)
Prism autohighlight runs only after all other JS has finished. This should be fine:
Don’t add it to the
wrap
hook inside ofcustomizeClasses
. I would do it like this:It is possible, that
__id
doesn’t exist. It is added on the fly by the_.util.objId()
function. In the rare event whereinsertBefore
is never called you would have no__id
fields:This should work in all cases, but I havn’t tested it:
The question is, if we should make the
language
parameter for thehighlight
function optional. Inside Prism the parameter is always supplied. You could use the above code just as easily in your plugin or before you call thehighlight
function.On the other hand we have examples on http://prismjs.com/ without the language parameter:
But this example was added only a few days ago with a PR. @LeaVerou What do you think?