Vite does not allow usage of JSX syntax within .js files by default.
I have already renamed my files to .jsx
(or .tsx
), but I have external dependencies that I cannot rename.
Example error from Vite:
✘ [ERROR] The JSX syntax extension is not currently enabled
node_modules/somelib/src/someFile.js:122:11:
122 │ return <div/>
How can I configure Vite to support JSX expressions in all .js files?
The vite.config.js
below makes Vite/Vitest treat *.js
files as JSX to avoid errors like:
Error: Failed to parse source for import analysis because the content contains invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.
vite.config.js
import { defineConfig, transformWithEsbuild } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [
{
name: 'treat-js-files-as-jsx',
async transform(code, id) {
if (!id.match(/src\/.*\.js$/)) return null
// Use the exposed transform from vite, instead of directly
// transforming with esbuild
return transformWithEsbuild(code, id, {
loader: 'jsx',
jsx: 'automatic',
})
},
},
react(),
],
optimizeDeps: {
force: true,
esbuildOptions: {
loader: {
'.js': 'jsx',
},
},
},
})
And don't forget to run npm i @vitejs/plugin-react
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With