#HMR doesn't work with .js file

1 messages · Page 1 of 1 (latest)

astral kelp
#

can anyone help me with this?
https://github.com/vitejs/vite/discussions/14649.

I'm trying to upgrade my react app with vite and I did most of the necessary parts. Now I'm facing a problem related to HMR.
I have a lots of .js file and I don't want to rename all of them to .jsx (.jsx works just fine with HMR). Here's my vite config.

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

function readPackageJson() {
  try {
    const packageJsonContent = fs.readFileSync('./package.json', 'utf8');
    return JSON.parse(packageJsonContent);
  } catch (error) {
    console.error('Error reading package.json:', error);
    return null; 
  }
}

const packageJson = readPackageJson();

export default defineConfig({
  server: {
    host: "localhost",
    port: 3000,
    open: true,
    proxy: {
      '/api': {
        target: packageJson.proxy,
        changeOrigin: true,
      }
    }
  },
  base: '/',
  plugins: [react({
    
    babel : {
      include: [/\.(j|t)sx?$/]
    }
  }) ],
  esbuild: {
    loader: "tsx",
    include: /src\/.*\.(j|t)sx?$/,
    exclude: []
  },
  optimizeDeps: {
    esbuildOptions: {
    loader : {
        ".js": "tsx",
    }
    },
  },

})

I've the loader as tsx because I have some type declaration in my .js file. With this setup, my app running in the development server perfectly but whenever I'm chaning my .js file, it shows page reload instead of HMR.
It's working with webpack5 and react-scripts5. Is there any way I can achieve hot refresh in my js file ?

void basin
#

This is not supported. Please use the correct file extension so that you don't have to configure every tool to parse JS file as something else. This should probably confuse most IDE also.
Also you should move the proxy setting from package.json to the vite config is not used by other tools, this will avoid to add readPackageJson

astral kelp
#

Thank you Arnaud for the response. It'll be hard for me to rename all .jsx file and I'll have to make a lot of changes (removing ts type annotations from .js file as .jsx doesn't ignore them.) I'd better be using react-scripts5 for this project.

void basin
#

You should rename to .tsx if you're using types no?