javascripthtmlnode.jsreactjsscrypt

How to run scripts in index.html in react if you don't have index.html


I am still new to React. I have React web App to which I need to add several scripts. Although scripts have to be inside of body tag in index.html. Like this :

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>React example</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style media="only screen">
      html,
      body,
      #root {
        height: 100%;
        width: 100%;
      }
    </style>
  </head>
  <body>
    <div id="root">Loading React example&hellip;</div>
      <script 
        src="https://unpkg.com/systemjs@0.19.39/dist/system.src.js"
       > 
       </script>
      <script src="systemjs.config.js"></script>
      <script>
        System.import('./index.jsx').catch(function(err) {
          console.error(err);
        });
      </script>
  </body>
</html>

But the problem is that my app doesn't have index.html it has only index.js. I tried to add this script with document.write but I think it's a wrong way of doing it. Besides that i have Semantic and Syntactic errors which I cannot understand they are also attached here


Solution

  • You can append the scripts in your react code with:

    let script = document.createElement("script");
    script.setAttribute("src", scriptUrl);
    script.setAttribute("type", "text/javascript");
    

    (this is for linked scripts, but embedded scripts can be done in a similar way)