TypeScript项目中如何保留knexfile.js并调整其导入路径?
解决TypeScript项目中Knex+SQLite的路径问题
1. 让TypeScript忽略knexfile.js
修改项目根目录的tsconfig.json,在exclude数组中加入knexfile.js,编译时就不会将该文件复制到build目录,保留在项目根目录:
{ "compilerOptions": { "outDir": "./build", // 其他已有配置 }, "exclude": [ "node_modules", "build", "knexfile.js" // 新增此行 ] }
2. 调整connect.ts的导入路径
在src/connect.ts中,放弃相对路径导入,改用基于项目根目录的绝对路径加载knexfile.js,避免编译后路径偏移问题。借助Node.js的path模块和process.cwd()(运行时指向项目根目录)实现:
import knex from 'knex'; import path from 'path'; // 直接加载根目录的knexfile.js const knexConfig = require(path.resolve(process.cwd(), 'knexfile.js')); // 按需选择环境配置,示例为development const db = knex(knexConfig.development); export default db;
3. 修正knexfile.js中的数据库路径
原knexfile.js用__dirname可能因导入位置变化导致路径错误,改成基于项目根目录的写法,确保数据库文件始终生成在根目录:
const path = require('path'); module.exports = { development: { client: 'sqlite3', connection: { filename: path.resolve(process.cwd(), 'dev.sqlite3') }, useNullAsDefault: true } };
4. 确保Knex迁移工具正常工作
因为knexfile.js保留在根目录,运行迁移命令时直接指定该文件即可,比如:
knex migrate:latest --knexfile ./knexfile.js
也可以在package.json的scripts中配置快捷命令:
{ "scripts": { "migrate": "knex migrate:latest --knexfile ./knexfile.js" } }
完成以上调整后,编译后的build/src/connect.js会正确加载根目录的knexfile.js,数据库文件将始终生成在项目根目录,不会出现在build文件夹内。
内容的提问来源于stack exchange,提问作者gui3
相关产品推荐
相关产品推荐

