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

如何从零配置Sequelize与Sequelize-CLI适配TypeScript?

Sequelize + TypeScript 从零配置指南(解决CLI模型生成/迁移问题)

1. 安装核心依赖

先清理可能冲突的旧依赖,再安装正确的包:

# 卸载可能冲突的包(可选)
npm uninstall sequelize-cli-typescript

# 安装生产依赖
npm install sequelize sequelize-typescript mysql2 # mysql2可替换为pg/sqlite3等对应数据库驱动

# 安装开发依赖
npm install -D typescript ts-node @types/node sequelize-cli

2. 初始化TypeScript配置

在项目根目录创建tsconfig.json,配置如下:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "CommonJS",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "resolveJsonModule": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

关键注意:experimentalDecorators和emitDecoratorMetadata必须设为true,否则sequelize-typescript的装饰器语法无法生效。

3. 编写Sequelize配置文件

在项目根目录创建sequelize.config.ts(TS格式):

import { Options } from 'sequelize';
import path from 'path';

const config: Record<string, Options> = {
  development: {
    username: 'your_db_username',
    password: 'your_db_password',
    database: 'your_db_name',
    host: 'localhost',
    dialect: 'mysql', // 替换为你的数据库类型:mysql/postgres/sqlite等
    models: [path.resolve(__dirname, 'src/models')],
    migrations: [path.resolve(__dirname, 'src/migrations')],
    seeders: [path.resolve(__dirname, 'src/seeders')],
    dialectOptions: {
      charset: 'utf8mb4'
    }
  },
  test: {
    // 测试环境配置,参考development字段修改
  },
  production: {
    // 生产环境建议用环境变量注入
    username: process.env.DB_USER,
    password: process.env.DB_PASS,
    database: process.env.DB_NAME,
    host: process.env.DB_HOST,
    dialect: 'mysql',
    models: [path.resolve(__dirname, 'dist/models')],
    migrations: [path.resolve(__dirname, 'dist/migrations')],
    seeders: [path.resolve(__dirname, 'dist/seeders')]
  }
};

export default config;

注意:生产环境需指向编译后的dist目录,开发环境直接使用src下的TS文件。

4. 配置package.json脚本

修改package.json的scripts字段,添加以下命令:

{
  "scripts": {
    "build": "tsc",
    "sequelize": "ts-node ./node_modules/sequelize-cli/lib/sequelize",
    "model:generate": "npm run sequelize model:generate",
    "migrate": "npm run sequelize db:migrate -- --config sequelize.config.ts",
    "migrate:undo": "npm run sequelize db:migrate:undo -- --config sequelize.config.ts",
    "migrate:undo:all": "npm run sequelize db:migrate:undo:all -- --config sequelize.config.ts",
    "seed:generate": "npm run sequelize seed:generate",
    "seed:run": "npm run sequelize db:seed:all -- --config sequelize.config.ts"
  }
}

核心:所有sequelize命令通过ts-node执行,确保能解析TS配置和模型文件;必须通过--config指定TS格式的配置文件。

5. 生成并验证模型

执行以下命令生成TS格式的模型和迁移文件:

npm run model:generate -- --name User --attributes username:string,email:string,password:string

生成的模型文件位于src/models/user.ts,确保内容符合sequelize-typescript规范:

import { Table, Column, Model, DataType } from 'sequelize-typescript';

@Table({
  tableName: 'users',
  timestamps: true // 默认开启createdAt/updatedAt字段
})
export class User extends Model<User> {
  @Column({
    type: DataType.STRING,
    allowNull: false,
    unique: true
  })
  username!: string;

  @Column({
    type: DataType.STRING,
    allowNull: false,
    unique: true,
    validate: {
      isEmail: true
    }
  })
  email!: string;

  @Column({
    type: DataType.STRING,
    allowNull: false
  })
  password!: string;
}

6. 执行迁移

确保目标数据库已创建,执行迁移命令:

npm run migrate

生产环境需先编译代码再迁移:

npm run build
npm run migrate -- --env production

常见问题排查

  • 生成JS文件而非TS:未通过ts-node运行sequelize-cli,或未指定TS配置文件,确保使用上述package.json中的脚本。
  • 迁移执行失败:检查tsconfig.json中experimentalDecorators是否开启;确认配置文件中的模型/迁移路径正确;核对数据库连接信息。
  • TS文件无法执行迁移:确保所有命令通过ts-node调用,避免直接使用原生sequelize-cli命令。

内容的提问来源于stack exchange,提问作者Mustafa Ahmed Mohammed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 18:45:32