reactjschess

How fixPGN file/game import with React app


I'm trying import a pgn file and its throwing an error, but if I rename the file to txt it works, but I prefer it like pgn instead renaming it.

// React app created with Vite: npm create vite@latest
// import pgn from "./pgn.txt"; // Import correctly
   import pgn from "./pgn.pgn"; // Uncaught SyntaxError: Unexpected string (at pgn.pgn?t=1720874180505&import:1:8)

// pgn.txt and pgn.pgn are the same file with different extension

let games = await fetch(pgn).then((data) => data.text().then((data) => data));

function App() {
  return <>{<h4>{games}</h4>}</>;
}

export default App;

Pgn File (pgn.pgn( throw error) or pgn.txt (works)), the files are equal

[Event "Troll Masters"]
[Site "Gausdal NOR"]
[Date "2001.01.05"]
[Round "1"]
[White "Edvardsen,R"]
[Black "Carlsen,Magnus"]
[Result "1/2-1/2"]
[WhiteElo "2055"]
[BlackElo "0"]
[ECO "D12"]

1.d4 Nf6 2.Nf3 d5 1/2-1/2

Error:

Uncaught SyntaxError: Unexpected string (at pgn.pgn?t=1720874180505&import:1:8)

Solution

  • You can add the query string ?url to the end of any import to get the URL of that file:

    import pgn from "./pgn.pgn?url"
    
    // You can now `fetch(pgn)`
    

    Also, you can import the contents of any file at compile time using ?raw which would eliminate the fetch call in this case:

    import pgn from "./pgn.pgn?raw"
    
    // pgn is now a string with the contents of `pgn.pgn`