経緯
Sequelizeのデフォルトは config.json
というファイル内でDBへの接続情報を管理しているので、 .env
などの環境変数で管理したかった。
結論
config/config.json
の中身を以下のようにモジュール化して、拡張子を .js
に変更する。
dotenv
で環境変数を読み込む。
config.js
require('dotenv').config();
module.exports = {
'development': {
'username': process.env.DB_USERNAME,
'password': process.env.DB_PASS,
'database': process.env.DB_DATABASE,
'host': process.env.DB_HOST,
'port': '3306',
'dialect': 'mysql',
'operatorsAliases': false,
},
};
model/index.js
の以下を編集を編集する。
index.js
// 編集前
const config = require(__dirname + '/../config/config.json')[env];
// 編集後
const config = require(__dirname + '/../config/config.js')[env];