使用typeorm+express+mysql搭建后台项目

763 阅读2分钟

使用typeorm+express+mysql搭建后台项目 文档地址:typeorm.biunav.com/zh/

  • 1、你可以通过运行typeorm init --name MyProject --database mysql --express来生成一个更高级的 Express 项目
typeorm init --name MyProject --database mysql --express
  • 目录结构
├── README.md
├── ormconfig.json
├── package-lock.json
├── package.json
├── src
│   ├── controller
│   │   └── UserController.ts
│   ├── entity
│   │   └── User.ts
│   ├── index.ts
├── tsconfig.json
└── yarn.lock

image.png

文件说明:

  • index.ts入口文件
  • User.ts定义表字段和类型文件 image.png

说明:@Entity中写表名称(不写默认为class的名称且为小写)

  • 2、修改ormconfig.json文件

image.png

文件说明:

  • host mysql主机的ip
  • port mysql服务的端口号
  • username mysql的用户名
  • password mysql的密码
  • database 数据库名称
  • 3、安装项目依赖
yarn
  • 4、修改packages.json文件,增加打包配置 image.png
  • 5、修改tsconfig.json文件,将输出目录修改为dist

image.png

  • 6、运行项目
yarn start
  • 7、build项目
yarn build
  • 8、测试打包后的文件是否能运行
node dist/index.js

说明:此时会报错 SyntaxError: Cannot use import statement outside a module at Object.compileFunction (node:vm:352:18) at wrapSafe (node:internal/modules/cjs/loader:1031:15) at Module._compile (node:internal/modules/cjs/loader:1065:27) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) at Module.load (node:internal/modules/cjs/loader:981:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Module.require (node:internal/modules/cjs/loader:1005:19) at require (node:internal/modules/cjs/helpers:102:18) at /Users/jydata/Desktop/workSpace/ormexpress/node_modules/typeorm/util/ImportUtils.js:29:52 image.png

原因:在当前项目目录运行时,默认会加载ormconfig.json文件配置,由于引入文件的路径不对,所以会报错(原先配置) image.png 解决方法:修改中entities、migrations、subscribers三个配置的路径为dist/xxxx(修改后) image.png 也可以把dist目录拷贝到其它位置运行,注意:测试完需要将entities、migrations、subscribers三个配置还原。

补充说明:在服务器上运行的时候需要将ormconfig.json文件中的entities、migrations、subscribers3项配置目录改为dist,src目录可以不上传到服务器,其它文件则需要上传

注意:dist文件夹需要在服务器上生成,不能把本地的dist直接上传,否则接口会报错