본문 바로가기
IT/Nodejs

node 환경변수 관리하는 방법

by DOSGamer 2022. 8. 29.
반응형

cross-env ?

모든 OS 환경에서 CLI 로 환경변수를 설정할 수 있다 테스트 하거나 배포할 때 환경을 설정하는 용도로 사용한다

설치

# npm
npm i -s cross-env

# Yarn
yarn add cross-env

사용

cross-env NODE_ENV=production node src/index.js
cross-env NODE_ENV=development node src/index.js
cross-env NODE_ENV=localhost node src/index.js

참조사이트

kentcdodds/cross-env
Run scripts that set and use environment variables across platforms Most Windows command prompts will choke when you set environment variables with NODE_ENV=production like that. (The exception is Bash on Windows, which uses native Bash.) Similarly, there's a difference in how windows and POSIX commands utilize environment variables.
https://github.com/kentcdodds/cross-env

dotenv ?

.env 파일을 환경변수에 대신 설정해주는 기능 개발 테스트 운영 환경별로 환경변수가 바뀔때 사용

설치

# npm
npm i -s dotenv

# Yarn
yarn add dotenv

사용

/* config.js */
import path from 'path'
import dotenv from 'dotenv'

if (process.env.NODE_ENV === 'production') {
  dotenv.config({ path: path.join(__dirname, 'path/to/.env.production') })
} else if (process.env.NODE_ENV === 'develop') {
  dotenv.config({ path: path.join(__dirname, 'path/to/.env.develop') })
} else {
  throw new Error('process.env.NODE_ENV를 설정하지 않았습니다!')
}

export const configs = {
	database: process.env.DATABASE || 'localhost',
	port: process.env.PORT || 4000,
	endpoint: process.env.ENDPOINT || 'http://localhost:4000'
}

/* service.js */
import { configs } from 'config'

const database = configs.database;
const port = configs.port;
const endpoint = configs.endpoint;

concurrently ?

command 를 멀티로 실행시키는 기능 npm 실행시에 client , server, db 를 동시에 실행시켜야 하는 경우 유용함

설치

# npm (global 로 설치하자)
npm i -g concurrently

사용

# terminal 에서 사용할 때
concurrently "command1 arg" "command2 arg"

# package.json 에서 script 로 사용할 때
"scripts": {
  "client": "...",
  "server": "...",
  "database": "...",
	"allstart": "concurrently --kill-others-on-fail \"npm run server\" \"npm run client\" \"npm run database\""
}

참조사이트

concurrently
master branch status Run multiple commands concurrently. Like npm run watch-js & npm run watch-less but better. Table of contents I like task automation with npm but the usual way to run multiple commands concurrently is npm run watch-js & npm run watch-css. That's fine but it's hard to keep on track of different outputs.
https://www.npmjs.com/package/concurrently

NPM 라이브러리 버전 업데이트

npm 라이브러리 버전을 업데이트 하는 방법

#npm package 설치
npm install -g npm-check-updates

#version 확인
ncu

#최신 version 으로 package.json 파일 업데이트 하기
ncu -u

#npm package 다시 설치하기
npm install

Uploaded by N2T

반응형