将 knex 与 es6 模块一起使用

pet*_*urs 5 javascript node-modules ecmascript-6 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
Run Code Online (Sandbox Code Playgroud)

但这不允许使用 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'
    }
  }

};
Run Code Online (Sandbox Code Playgroud)
//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"
}
Run Code Online (Sandbox Code Playgroud)

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

"dependencies": {
    "knexfile": "file:./knex",
    ...
Run Code Online (Sandbox Code Playgroud)

我可以毫无顾虑地导入配置

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

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

export default myknex
Run Code Online (Sandbox Code Playgroud)

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

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

先感谢您

Mik*_*stö 5

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

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

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

export default myknex
Run Code Online (Sandbox Code Playgroud)