将nex与es6模块一起使用

时间:2020-03-23 10:38:35

标签: javascript ecmascript-6 node-modules knex.js

我正在做一个完全基于ES6模块的项目,在集成knex尤其是knex CLI时遇到一些困难

我可以使用knex(不使用CLI):


 const config = {
  client: 'mysql2',

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

  },
}

const myknex = knex(config )

export default myknex

但这不允许使用knex CLI ...

所以我创建了一个带有.knex / knexfile.js文件和.knex / package.json文件的knexfile模块:

//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"
}

我可以在项目中添加一个knexfile模块

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

我可以毫无后顾之忧地导入配置

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

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

export default myknex

但是我必须指定开发或生产,不能像knex CLI那样管理ENV

如何在ES6项目中更简单有效地使用knex和knex CLI?

提前谢谢

1 个答案:

答案 0 :(得分:2)

您可以定义环境变量NODE_PROFILE=production,以便CLI将自动选择生产配置。如果愿意,可以在应用程序代码中使用相同的env变量,如下所示:

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

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

export default myknex
相关问题