Vercel dev tells vite to parse html as javascript

Hey folks!

I have a vite+react project written in Typescript. When running the project via vite everything works as expected.

I have added the following vercel.json to support SPA navigation:

{
  "$schema": "https://openapi.vercel.sh/vercel.json",
  "rewrites": [
    {
      "source": "/(.*)",
      "destination": "/index.html"
    }
  ]
}

This causes an error when I try to run the app via vercel dev:

[vite] Internal server error: Failed to parse source for import analysis because the content contains invalid JS syntax. You may need to install appropriate plugins to handle the .html file format, or if it’s an asset, add “**/*.html” to assetsInclude in your configuration.

Gemini is utterly bamboozled as to why this doesn’t work, so I figure I’d ask some real people :slight_smile:

For added context, I would also like to host this app’s serverless functions in the /api directory, which I anticipate requiring the following addition to the vercel.json:

{
  "$schema": "https://openapi.vercel.sh/vercel.json",
  "rewrites": [
    {
      "source": "/api/(.*)",
      "destination": "/api/$1"
    },
    {
      "source": "/(.*)",
      "destination": "/index.html"
    }
  ]
}

However, we’re not quite there yet. Any idea what I’m doing wrong?

1 Like

Hey John, I ran into the exact same problem. The reproduction is simple: take an SPA Vite example project like Vite - React and add vercel.json exactly as you provided:

{
  "$schema": "https://openapi.vercel.sh/vercel.json",
  "rewrites": [
    {
      "source": "/(.*)",
      "destination": "/index.html"
    }
  ]
}

The problem is that vercel dev proxy will rewrite all requests to /index.html, including requests for .js files – you can confirm it by visiting http://localhost:3000/src/main.tsx (or whatever is the path of JS file linked from index.html). This will result in Vite attempting to parse HTML file as JS.

For the SPA rewrite I managed to solve it using vite-vercel-plugin with the following configuration in vite.config.js:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react'; // probably not needed
import vercel from 'vite-plugin-vercel';

export default defineConfig({
  vercel: {
    rewrites: [
      {
        source: '/(.*)',
        destination: '/index.html',
      },
    ],
  },
  plugins: [react(), vercel()],
});

I have yet to try the serverless functions (although I will rather use just rewrite to external API), but apparently it should be supported by the plugin as well.

2 Likes

Yeah we recommend using the Vite plugin here

The key issue is making sure it serves static files statically. If that doesn’t happen, then it invokes the server handler which will run through the rewrites