Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mjclemente/e74c33ab326e50ea5a961edfc847467c to your computer and use it in GitHub Desktop.
Save mjclemente/e74c33ab326e50ea5a961edfc847467c to your computer and use it in GitHub Desktop.
Knex.js & TypeScript config example · How to setup Knex.js in a TypeScript project
import * as Knex from 'knex';
export async function up(knex: Knex): Promise<any> {
return knex.schema.createTable('test_setup', (table: Knex.TableBuilder) => {
table.integer('foobar');
});
}
export async function down(knex: Knex): Promise<any> {
return knex.schema.dropTable('test_setup');
}
require('ts-node/register');
module.exports = {
client: 'pg',
connection: process.env.DATABASE_URL,
pool: {
min: 2,
max: 10
},
migrations: {
tableName: 'knex_migrations',
directory: 'migrations'
},
timezone: 'UTC'
};
{
"name": "my-app",
"version": "0.0.1",
"description": "",
"main": "src/server.js",
"private": true,
"scripts": {
"knex:migrate:make": "knex --knexfile src/database/knexfile.ts -x ts migrate:make",
"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.16.3",
"pg": "^7.9.0",
"ts-node": "^8.1.0",
"typescript": "^3.3.4000"
}
}

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