Some users may want to inject their styles into the DOM like v1. There is no equivalent for this functionality in the second version so we can define our injectStyle function as following:
// inject-style.tsfunctioncaseConverter(str:string):string {if (str.length===0) return str;constisUppercase= str[0] === str[0].toUpperCase();constresult= str.split(/(?=[A-Z])/).join("-").toLowerCase();return isUppercase ?`-${result}`: result;}// CSS object to string converter.exportfunctiontoCss(obj:any):string {if (!obj ||typeof obj !=="object"||Array.isArray(obj)) {thrownewTypeError(`expected an argument of type object, but got ${typeof obj}` ); }let lines:string[] = [];for (let index =0; index <Object.keys(obj).length; index++) {constid=Object.keys(obj)[index];constkey=caseConverter(id);constvalue= obj[id];if (typeof value ==="object") {consttext=toCss(value);lines.push(`${id}{${text}}`); } else {lines.push(`${key}:${value};`); } }returnlines.join("");}// Inject string/object style to DOM.exportfunctioninjectStyle( textOrObject:string|object, id?:string, overridable =true, hostElement:HTMLElement=document.head) {if (!textOrObject ||Array.isArray(textOrObject)) return;if (typeof textOrObject ==='string'&&textOrObject.length===0) return;if (id) {let oldStyle =document.getElementById(id);if (oldStyle) {let isStyleTag =oldStyle.tagName.toLowerCase() ==="style";if (!isStyleTag) {thrownewError("The provided id does not indicate a style tag."); } elseif (isStyleTag && overridable) {oldStyle.innerHTML =typeof textOrObject ==="object"?toCss(textOrObject) : textOrObject; }return; } }let style =document.createElement("style");style.type ="text/css";style.innerHTML =typeof textOrObject ==="object"?toCss(textOrObject) : textOrObject;if (id) style.id = id;hostElement.appendChild(style);}
You can use css-to-js transformer to convert a CSS text to a JS object and use the result for toCss(result) directly!
There is a conventional naming approach for defining your rules. Every uppercase character will change to a hyphen and a lowercase character (XyZ => -xy-z). For example, If you want to achieve -webkit-animation you should write WebkitAnimation or flexDirection will change to flex-direction.
This is exactly what the caseConverter function does.