Reputation: 1559
I am making a react app with vite instead of creat react app. When I use .jsx as suffix, it works fine. But when I use .js, throws hundreds of errors in my files, such as:
Layout.js:131:9: error: Unexpected "<"
I've read this in twitter from Evan You but is there no way? As far as I used this code in vite.config.ts file:
import { defineConfig } from 'vite'
export default defineConfig(() => ({
esbuild: {
loader: 'jsx',
},
optimizeDeps: {
esbuildOptions: {
loader: {
'.js': 'jsx',
},
},
},
})
but it still didn't work! Could you possibly help me?
Upvotes: 6
Views: 8355
Reputation: 978
Try the below Vite configuration. This configuration worked for me. But in every js file, need to import React.
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { resolve } from 'path';
import fs from 'fs/promises';
// https://vitejs.dev/config/
export default defineConfig({
resolve: {
alias: {
src: resolve(__dirname, 'src'),
},
},
esbuild: {
loader: 'jsx',
include: /src\/.*\.jsx?$/,
exclude: [],
},
optimizeDeps: {
esbuildOptions: {
plugins: [
{
name: 'load-js-files-as-jsx',
setup(build) {
build.onLoad(
{ filter: /src\\.*\.js$/ },
async (args) => ({
loader: 'jsx',
contents: await fs.readFile(args.path, 'utf8'),
})
);
},
},
],
},
},
plugins: [react()],
});
Upvotes: 8