Home > Mobile >  import Css file from directory to inject in iframe head tag like <style> Vite React JS
import Css file from directory to inject in iframe head tag like <style> Vite React JS

Time:10-16

welcome to my ***** problem

I am spending some days trying to resolving something.

I am trying to create a webpage editor with Grapes JS, React JS and Vite everything was wonderful until the kingdom of creating different themes appears...

The themes are in different plugins, this plugins are in the project running from the react app, my problem is when i try to load a css file in the directory of the plugin :

import styles from "../../dist/main.css";

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

cssStyle.innerHTML =  styles ;
    const doc = iframe.contentDocument;
    const f = setInterval(() => {
        if (doc.readyState === "complete") {
            doc.head.appendChild(cssStyle);
            clearInterval(f);
        }
    }, 100);

This styles are apply globally in my react app and i only want to inject in a iframe, in the head tag.

Is any way to load a css file in react without compile globally this css file?

Thanks by the help

CodePudding user response:

Vite automatically injects CSS styles into the page when you import a .css file. Quite helpful... until it's not. From what you describe I'm betting that is the culprit.

There is a way to disable that behavior: it looks like adding ?inline to the filename will disable the injection and just grab the file contents. So your first line would look like this:

import styles from "../../dist/main.css?inline";

That should give you styles as a pure string, and the rest of your code should then work.

P.S. Welcome to StackExchange :)

  • Related