我要使用process.env
-这是db.js-
import * as dotenv from "dotenv";
import mongoose from "mongoose";
dotenv.config();
const { DB_URL } = process.env.PRODUCTION ? process.env : "localhost:27017/save-idiot";
const { DB_PROTOCOL } =process.env.PRODUCTION ? process.env : "mongodb"
mongoose.connect(`${DB_PROTOCOL}://${DB_URL}`, {
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true
});
const db = mongoose.connection;
const handleOpen = () => console.log("✅ Connected to DB");
const handleError = error => console.log(`❌ Error on DB Connection:${error}`);
db.once("open", handleOpen);
db.on("error", handleError);
-package.json-
"scripts": {
"dev:server": "nodemon --exec babel-node src/init.js -- delay 2",
"dev:assets": "cd src && WEBPACK_ENV=development webpack -w",
"lint": "eslint src/",
"fix": "eslint --fix src/",
"clean": "rm -rf build",
"build:server": "babel src --out-dir build --ignore 'src/assets','src/static','src/webpack.config.js'",
"build:assets": "cd src && WEBPACK_ENV=production webpack",
"copy:static": "cp -R src/static src/views build/",
"build": "npm run clean && npm run lint && npm run build:server && npm run build:assets && npm run copy:static",
"start": "PRODUCTION=true forever start build/init.js"
}
const { DB_URL } = process.env.PRODUCTION ? process.env : "localhost:27017/save-idiot";
const { DB_PROTOCOL } =process.env.PRODUCTION ? process.env : "mongodb"
如果我npm运行dev:server, 我想获取“ localhost:27017 / save-idiot”和“ mongodb”
如果我npm开始, 我想获取process.env
我该怎么做?
答案 0 :(得分:0)
您可以使用cross-env
包,它用于设置环境变量。
安装后,您可以尝试如下操作:
"start": "cross-env PRODUCTION=true forever start build/init.js"
答案 1 :(得分:0)