Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Context doesn't compile on Vite

I am trying to implement a small context store for my React project. I copied most of this code from a previous (working) project and changed the variable names - the biggest difference was I changed to Vite+SWC.

This is the code.

import { createContext, useState } from "react";
import { GameContextProviderProps } from "./PropTypes";

export interface IGameContext {
  completedWinds: number;
  setCompletedWinds: (newCompletedWinds: number) => void;
};

const GameContext = createContext<IGameContext>({
  completedWinds: 0,
  setCompletedWinds: () => { }
});

const GameContextProvider = ({ children }: GameContextProviderProps) => {
  const [completedWinds, setCompletedWinds] = useState(0);

  const initialContext: IGameContext = {
    completedWinds,
    setCompletedWinds,
  };

  return <GameContext.Provider value={ initialContext }> {children} < /GameContext.Provider>
};

export default GameContextProvider;

This is my vite config

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
})

This is the error

4:58:25 pm [vite] Internal server error:
  × Expected '>', got 'value'
    ╭─[/Users/gg/Code/mahjong-points/src/GameContext.ts:73:1]
 73 │     setCompletedWinds,
 74 │   };
 75 │
 76 │   return <GameContext.Provider value={ initialContext }> { children } < /GameContext.Provider>
    ·                                ─────
 77 │ };
 78 │
 79 │ export default GameContextProvider;
    ╰────


Caused by:
    Syntax Error
  Plugin: vite:react-swc
  File: /Users/gg/Code/mahjong-points/src/GameContext.ts:73:1

Removing the value prop gives the error Cannot find namespace 'GameContext' - but I declared it just a few lines above. I also tried the @vitejs/plugin-react but the same error occured.

like image 613
XeonFusion Avatar asked Oct 12 '25 11:10

XeonFusion


2 Answers

Your code should probably be in a .tsx file instead of .ts.

like image 85
Guillaume Brunerie Avatar answered Oct 14 '25 01:10

Guillaume Brunerie


Even I faced similar issues with .js file extension. Changing it to .jsx fixed the error

like image 31
Priyadarshini Karanth Avatar answered Oct 14 '25 01:10

Priyadarshini Karanth