Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save voidnerd/2ec33d99afd7bc56a3c167a4a1973bc9 to your computer and use it in GitHub Desktop.
Save voidnerd/2ec33d99afd7bc56a3c167a4a1973bc9 to your computer and use it in GitHub Desktop.
How to use Knex.js in a TypeScript project
import { Knex } from 'knex'
export async function up(knex: Knex): Promise<any> {
await knex.schema.createTable('test_setup', (table: Knex.TableBuilder) => {
table.integer('foobar');
});
}
export async function down(knex: Knex): Promise<any> {
await knex.schema.dropTable('test_setup');
}
import { Knex } from "knex";
const config: Knex.Config = {
client: "pg",
connection: {
connectionString: process.env.DATABASE_URL,
timezone: "utc",
},
pool: {
min: 2,
max: 10,
},
migrations: {
tableName: "knex_migrations",
directory: "migrations",
},
};
export default config;
{
"name": "my-app",
"version": "0.0.1",
"description": "",
"main": "src/server.js",
"private": true,
"scripts": {
"knex:migrate:make": "knex --knexfile src/database/knexfile.ts migrate:make -x ts",
"knex:migrate:latest": "knex --knexfile src/database/knexfile.ts migrate:latest",
"knex:migrate:rollback": "knex --knexfile src/database/knexfile.ts migrate:rollback"
},
"dependencies": {
"knex": "^0.95.6",
"pg": "^8.6.0",
"ts-node": "^9.1.1",
"typescript": "^4.2.4"
}
}

Create migration files

This creates a .ts file in migrations directory

npm run knex:migrate:make -- some-migration-name

Run migrations

npm run knex:migrate:latest

Rollback

npm run knex:migrate:rollback

Knex TypeScript issues

  • knexfile.ts requires require('ts-node/register'); to work.
  • ES6/ES2015 module syntax does not work in knexfile or in any files that it require()s

knex/knex#3003

knex/knex#2998

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment