Search code examples
reactjsviteswc-compiler

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.


Solution

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