Rajkumar Gaur
Rajkumar Gaur

Reputation: 135

Script tag in React throwing Uncaught SyntaxError: Unexpected token '<'

I want to add a script file to a jsx element.

The script file contains a simple console.log('script ran') and nothing else (I want to add an actual script file, but for testing purpose I chose this minimal code).

// editor.js

console.log('script ran')
// App.jsx

import React, { useEffect } from 'react'

const App = () => {
  useEffect(() => {
    const script = document.createElement('script')
    script.src = '/editor.js'
    document.body.appendChild(script)
  }, [])

  return <></>
}

This throws the error below

Uncaught SyntaxError: Unexpected token '<' at editor.js 1:1

Folder Structure:

/
package.json
editor.js
src/
  App.js
  index.js

I have tried adding type="text/javascript", type="text/babel", async=true but nothing seems to work.

When I inspect the editor.js file in the developer tools, it shows an html file (The 404 page of my website)

When using type="text/babel" it doesnt throw any error, but also doesnt execute the script (console.log is never printed)

What am I doing wrong here? Also, I would like a solution which doesnt use React Helmet

React version: 17.0.1 (created with create-react-app)

Upvotes: 0

Views: 1097

Answers (1)

Konrad
Konrad

Reputation: 24651

You never serve the script and it's not accessible from the browser.

When you try to access /editor.js you are getting index.html, because that's how webpack's config for react works.

You should move your script to public

const App = () => {
  useEffect(() => {
    const script = document.createElement('script')
    script.src = process.env.PUBLIC_URL + '/editor.js'
    document.body.appendChild(script)

    // remember to remove the script
    return () => script.remove()
  }, [])

  return <></>
}

You didn't say anything about what development server you are using, but I guess it's create-react-app

Upvotes: 6

Related Questions