TypeORM MySQLDataSource未定义问题求助
问题:TypeORM中引用MySQLDataSource时触发ReferenceError
我用Node.js+Express开发微服务,采用TypeORM搭配MySQL实现数据库映射。严格按照官方文档完成配置后,调试时发现Repository.ts里引用MySQLDataSource会报错,提示ReferenceError: MySQLDataSource is not defined。这是我第一次使用TypeORM,求解决办法。
相关代码
data-source.ts
import "reflect-metadata"; import {DataSource} from 'typeorm'; /** * Various data source can be configured here */ export const MySQLDataSource = new DataSource({ type: "mysql", host: "localhost", port: 3306, username: "root", password: "password", database: "ignite_tuition_node_db", entities: ["dist/entities/*.js"], logging: true, synchronize: true, entitySkipConstructor: true, });
index.ts
import "reflect-metadata"; import express, { Application } from "express"; const expressApp = require('./express-app'); const StartServer = async() => { // initialize the application server const app: Application = express(); const PORT = process.env.PORT || 8000; await expressApp(app); // listen to the application server on PORT app.listen(PORT, (): void => { console.log(`Express application server running on address=> http://localhost:${PORT}`); }); } StartServer();
express-app.ts
/** * Express app */ module.exports = async (app: Application) => { // initialize mysql datasource MySQLDataSource.initialize() .then(() => console.log("MySQL Datasource has been successfully initialized")) .catch((e) => console.error("Error initializing mysql datasource", e)); // configuring necessary properties for server app.use(express.json()); // controller configuration TuitionController(app); }
Repository.ts
export function getRepository(entity: any): Repository<any> { try { return MySQLDataSource.getRepository(entity); } catch (e) { throw new TuitionServiceException(`Error occurred when finding ${entity} repository`); } }
报错信息
MySQLDataSource Uncaught ReferenceError ReferenceError: MySQLDataSource is not defined at eval (repl:1:1)
解决步骤
1. 补全缺失的导入语句
express-app.ts和Repository.ts都直接使用了MySQLDataSource,但没有从data-source.ts导入该变量,这是报错的核心原因。
- 修改
express-app.ts,添加必要导入:
import { Application } from "express"; import { MySQLDataSource } from "./data-source"; // 导入数据源 import { TuitionController } from "./your-tuition-controller-path"; // 同时导入控制器,否则也会报错
注意替换./your-tuition-controller-path为TuitionController实际的文件路径。
- 修改
Repository.ts,添加必要导入:
import { Repository } from "typeorm"; import { MySQLDataSource } from "./data-source"; // 导入数据源 import { TuitionServiceException } from "./your-exception-path"; // 导入自定义异常类
2. 统一模块导入规范
代码里同时混用了ESModule(import)和CommonJS(module.exports/require),可能导致模块加载异常,建议统一用ESModule:
- 修改
express-app.ts的导出方式:
import { Application } from "express"; import { MySQLDataSource } from "./data-source"; import { TuitionController } from "./your-tuition-controller-path"; export default async (app: Application) => { app.use(express.json()); TuitionController(app); }
- 修改
index.ts的导入方式:
import "reflect-metadata"; import express, { Application } from "express"; import expressApp from './express-app'; // 改用ESModule导入 const StartServer = async() => { const app: Application = express(); const PORT = process.env.PORT || 8000; await expressApp(app); app.listen(PORT, () => { console.log(`Express application server running on address=> http://localhost:${PORT}`); }); } StartServer();
3. 确保数据源先于业务代码初始化
避免在数据源未初始化时调用getRepository,可以把数据源初始化逻辑移到启动入口:
修改index.ts:
import "reflect-metadata"; import express, { Application } from "express"; import expressApp from './express-app'; import { MySQLDataSource } from "./data-source"; const StartServer = async() => { // 优先初始化数据源 try { await MySQLDataSource.initialize(); console.log("MySQL Datasource has been successfully initialized"); } catch (e) { console.error("Error initializing mysql datasource", e); process.exit(1); // 初始化失败直接终止进程 } const app: Application = express(); const PORT = process.env.PORT || 8000; await expressApp(app); app.listen(PORT, () => { console.log(`Express application server running on address=> http://localhost:${PORT}`); }); } StartServer();
内容的提问来源于stack exchange,提问作者CleanCodeOnline
相关产品推荐
相关产品推荐

