You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Nuxt 3中使用TypeORM遭遇[vite-node]解析错误求助

在Nuxt 3中使用TypeORM遇到解析错误问题

版本信息

  • nuxt@3.12.3
  • typeorm@0.3.20

配置步骤

1. 添加TypeORM插件

// plugins/typeorm.ts
import 'reflect-metadata';
import { defineNuxtPlugin } from '#app';
import { DataSource } from 'typeorm';
import { Events } from './../server/models/Events';

export default defineNuxtPlugin(async (nuxtApp) => {
  const AppDataSource = new DataSource({
    type: 'sqlite',
    database: 'database.sqlite',
    synchronize: true,
    logging: true,
    entities: [Events],
    migrations: [],
    subscribers: [],
  });

  if (!AppDataSource.isInitialized) {
    await AppDataSource.initialize();
  }

  nuxtApp.provide('db', AppDataSource);
});

2. 更新Nuxt配置文件

// nuxt.config.ts
import vuetify, { transformAssetUrls } from 'vite-plugin-vuetify';

export default defineNuxtConfig({
  devtools: { enabled: true },
  build: {
    transpile: ['vuetify'],
  },
  modules: [
    (_options, nuxt) => {
      nuxt.hooks.hook('vite:extendConfig', (config) => {
        config.plugins.push(vuetify({ autoImport: true }));
      });
    },
    '@nuxt/eslint',
    '@nuxt/test-utils/module',
  ],
  plugins: ['~/plugins/typeorm'],
  vite: {
    vue: {
      template: {
        transformAssetUrls,
      },
    },
  },
  typescript: {
    tsConfig: {
      compilerOptions: {
        target: 'es2020',
        module: 'ESNext',
        lib: ['dom', 'es2020'],
        moduleResolution: 'node',
        experimentalDecorators: true,
        emitDecoratorMetadata: true,
        strict: true,
        esModuleInterop: true,
        skipLibCheck: true,
        forceConsistentCasingInFileNames: true,
        baseUrl: '.',
      },
    },
  },
  nitro: {
    esbuild: {
      options: {
        tsconfigRaw: {
          compilerOptions: {
            experimentalDecorators: true,
          },
        },
      },
    },
  },

  compatibilityDate: '2024-07-25',
});

3. 创建TypeORM实体

// server/models/Events.ts
import 'reflect-metadata';
import { Column, CreateDateColumn, Entity, PrimaryColumn, UpdateDateColumn } from 'typeorm';

@Entity()
export class Events {
  @PrimaryColumn({ type: 'varchar', unique: true, nullable: false })
  id!: string;

  @Column({ type: 'text', nullable: false })
  name!: string;

  @Column({
    type: 'datetime',
  })
  start_date_time!: string;

  @Column({ type: 'text', nullable: false })
  location!: string;

  @Column({ type: 'int', nullable: false })
  distance!: number;

  @Column({ type: 'float', nullable: true })
  elevation!: number;

  @Column({ type: 'text', nullable: false })
  website!: string;

  @Column({ type: 'text', nullable: true })
  logo!: string;

  @Column({ type: 'text', nullable: true })
  background_color!: string;

  @CreateDateColumn()
  created_at!: Date;

  @UpdateDateColumn()
  updated_at!: Date;
}

4. 编写API接口

// server/api/events.ts
import { Events } from '../models/Events';
import { defineEventHandler, readBody } from 'h3';
import type { DataSource } from 'typeorm';

export default defineEventHandler(async (event) => {
  const appDataSource = event.context.nuxtApp.$db as DataSource;
  const eventsRepository = appDataSource.getRepository(Events);

  if (event.node.req.method === 'GET') {
    const events = await eventsRepository.find();
    return events;
  } else if (event.node.req.method === 'POST') {
    const body = await readBody(event);
    const events = eventsRepository.create(body);
    await eventsRepository.save(events);
    return events;
  }
});

启动日志(无报错)

$ yarn dev
yarn run v1.22.22
$ nuxt dev
Nuxt 3.12.3 with Nitro 2.9.7                                                                                                    18:14:08
                                                                                                                                18:14:08
  ➜ Local:    http://localhost:3000/
  ➜ Network:  use --host to expose

  ➜ DevTools: press Shift + Alt + D in the browser (v1.3.9)                                                                     18:14:09

ℹ Vite server warmed up in 2579ms                                                                                              18:14:13
ℹ Vite client warmed up in 2885ms                                                                                              18:14:13
✔ Nuxt Nitro server built in 708 ms                                                                                      nitro 18:14:13

遇到的问题

启动服务器时无任何错误或警告,但浏览器访问时出现500错误:

浏览器显示500错误:[vite-node] [PARSE_ERROR] /server/models/Events.ts

浏览器控制台仅显示:
控制台错误:GET http://localhost:3000/ [HTTP/1.1 500 Vite Error 1035ms]

请问有人遇到过这类错误吗?有没有人成功在Nuxt 3中使用TypeORM?


内容的提问来源于stack exchange,提问作者nicodel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 11:24:53