Home > OS >  import a css file into a javascript to convert it to a string
import a css file into a javascript to convert it to a string

Time:11-03

i am not sure if is possible to do in plain js

i am trying to add some styles to a style tag loading from a css file,

My problem is, i don't know how to read the file to transform in a string

I can't find a solution to do something like

import baseStyle from "./css/style.css"
//or
const baseStyle require("./css/style.css")

so the idea is parse in the html

        
const cssStyle = document.createElement("style");
        
cssStyle.innerHTML = baseStyle;

const doc = iframe.contentDocument;
doc.head.appendChild(cssStyle)


I am using GrapesJs, i am trying to parse some css from a framework

Thanks for the help

I try to load the css from several ways but nothing works

CodePudding user response:

You could try using fetch to get the file as text.

Something like this:

async function setCss() {
    const baseStyle = await fetch("./css/style.css").then(res => res.text())
    
    const cssStyle = document.createElement("style");
    
    cssStyle.innerHTML = baseStyle;

    const doc = iframe.contentDocument;
    doc.head.appendChild(cssStyle)
}
  • Related