How do i enable "@babel/plugin-proposal-decorators" with vite

Viewed 3523
 > src/App.jsx:22:0: error: Unexpected "@"
    22 │ @observer

error when starting dev server:
Error: Build failed with 1 error:
src/App.jsx:22:0: error: Unexpected "@"

I use the observer as a decorator then i got the error. Can not find a place to enable this option in documentation.

4 Answers

Vite's react plugin already supports this. Check the docs here https://github.com/vitejs/vite/tree/main/packages/plugin-react#proposed-syntax. You need not install any new packages. The following configuration should work,

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [reactSupport({
    babel: {
      parserOpts: {
        plugins: ['decorators-legacy', 'classProperties']
      }
    }
  })],
  server: {
    port: 3000
  }
});

I made a package called vite-plugin-babel-dev that runs babel during dev part in Vite, if you don't need full react plugin.

Install @babel/plugin-proposal-decorators and use it like this:

import { defineConfig } from 'vite';
import babelDev from 'vite-plugin-babel-dev';

export default defineConfig({
    plugins: [
        babelDev({
            babelConfig: {
                plugin: ['@babel/plugin-proposal-decorators']
            }
        }),
        // ...
    ],

    // ...
})

Edit: The package is now called just vite-plugin-babel

Not sure if you're using react but you can add babel plugins via the react plugin described here https://www.npmjs.com/package/@vitejs/plugin-react

The recomended setup seems to require you to rename your files to .ts / .tsx. However, the following is allowing me to keep the .js / .jsx extensions.

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

// https://vitejs.dev/config/
// https://www.npmjs.com/package/@vitejs/plugin-react
export default defineConfig({
    plugins: [
        react({
            babel: {
                plugins: [
                    ["@babel/plugin-proposal-decorators", { legacy: true }],
                    [
                        "@babel/plugin-proposal-class-properties",
                        { loose: true },
                    ],
                ],
            },
        }),
    ],
});

Related