【问题标题】:How do i enable "@babel/plugin-proposal-decorators" with vite如何使用 vite 启用“@babel/plugin-proposal-decorators”
【发布时间】:2022-02-04 15:50:50
【问题描述】:
 > 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 "@"

我使用观察者作为装饰器然后我得到了错误。在文档中找不到启用此选项的位置。

【问题讨论】:

    标签: javascript vite


    【解决方案1】:

    Vite 的 react 插件已经支持这个。 在此处查看文档 https://github.com/vitejs/vite/tree/main/packages/plugin-react#proposed-syntax。您无需安装任何新软件包。以下配置应该可以工作,

    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
      }
    });
    
    

    【讨论】:

      【解决方案2】:

      不确定你是否在使用 react,但你可以通过这里描述的 react 插件添加 babel 插件https://www.npmjs.com/package/@vitejs/plugin-react

      推荐的设置似乎要求您将文件重命名为.ts / .tsx。但是,以下允许我保留 .js / .jsx 扩展名。

      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 },
                          ],
                      ],
                  },
              }),
          ],
      });
      
      

      【讨论】:

        【解决方案3】:

        如果你不需要完整的 react 插件,我制作了一个名为 vite-plugin-babel-dev 的包,它在 Vite 的开发部分运行 babel。

        安装@babel/plugin-proposal-decorators并像这样使用它:

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

        编辑:这个包现在被称为vite-plugin-babel

        【讨论】:

          【解决方案4】:

          不,你不能。必须等待此问题解决:https://github.com/vitejs/vite/issues/2238

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-11-01
            • 1970-01-01
            • 2019-05-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多