【问题标题】:use of knex with es6 modules将 knex 与 es6 模块一起使用
【发布时间】:2020-07-03 19:39:19
【问题描述】:

我正在做一个完全基于 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

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

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

提前谢谢你

【问题讨论】:

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


    【解决方案1】:

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

    import knex from 'knex'
    import knexfile from 'knexfile'
    
    const myknex = knex(knexfile[process.env.NODE_PROFILE])
    
    export default myknex
    

    【讨论】:

      猜你喜欢
      • 2019-10-12
      • 1970-01-01
      • 2020-03-15
      • 2020-02-12
      • 2021-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多