use of knex with es6 modules

Viewed 4051

I am doing a project entirely based on ES6 modules and I have some difficulties integrating knex and especially knex CLI

I was able to use knex (without CLI) with this :


 const config = {
  client: 'mysql2',

  connection: { 
    host : "localhost", 
    user : "tata",  
    password : "tata",  
    database : "tata",

  },
}

const myknex = knex(config )

export default myknex

But this does not allow to use knex CLI...

So I created a knexfile module with a .knex/knexfile.js file and a .knex/package.json file :

//knexfile.js
module.exports =  {

  development: {
    client: 'sqlite3',
    connection: {
      filename: './dev.sqlite3'
    },
    useNullAsDefault : true
  },

  production: {
    client: 'mysql2',  
    connection: { 
      host : "localhost", 
      user : "tata",  
      password : "tata",  
      database : "tata",

    },  
    migrations: {
      tableName: 'knex_migrations'
    }
  }

};
//package.json
{
  "name": "knexfile",
  "version": "1.0.0",
  "description": "",
  "main": "knexfile.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

there I can add a knexfile module to my project

"dependencies": {
    "knexfile": "file:./knex",
    ...

and I can import the config without worries

import knex from 'knex'
import knexfile from 'knexfile'

const myknex = knex(knexfile.developpement)
//const myknex = knex(knexfile.production)

export default myknex

but I must specify development or production, ENV is not managed as knex CLI manages it

How can I use knex and knex CLI more simply and effectively in an ES6 project?

Thank you in advance

1 Answers

You can define environment variable NODE_PROFILE=production so that CLI will choose automatically production configuration. If you like you can use the same env variable in your application code like this:

import knex from 'knex'
import knexfile from 'knexfile'

const myknex = knex(knexfile[process.env.NODE_PROFILE])

export default myknex
Related