import yargs from 'yargs/yargs';
import { hideBin } from 'yargs/helpers';
import { lookItUp } from 'look-it-up';
import Dotenv from 'dotenv';
import fs from 'fs';
// https://fe-developers.kakaoent.com/2021/211125-create-12factor-app-with-nextjs/
// https://fe-developers.kakaoent.com/2022/220505-runtime-environment/
async function parseDotenv(appEnv) {
  // dotenv 파싱
  const envFilePath = await lookItUp(`.env.${appEnv}`);
  const parsedEnv = Dotenv.config({ path: envFilePath }).parsed || {};
  return parsedEnv;
}

async function copyEnv(appEnv) {
  // 파싱 대상 파일은 '.env'파일로 복사
  const envFilePath = await lookItUp(`.env.${appEnv}`);
  const dotenvFilePath = `${fs.realpathSync(process.cwd())}/.env`;
  fs.copyFileSync(envFilePath, dotenvFilePath);
}

function writeEnv(parsedEnv) {
  // 파싱 된 내용을 /public/__ENV.js에 출력
  const scriptFilePath = `${fs.realpathSync(process.cwd())}/public/__ENV.js`;
  fs.writeFileSync(scriptFilePath, `window.__ENV = ${JSON.stringify(parsedEnv)}`);
}

yargs(hideBin(process.argv))
  .command(
    'next-env',
    'Create Next.js runtime environment js',
    function builder(y) {
      return y.option('env', {
        alias: 'e',
        type: 'string',
        description: 'Environment name(ex: alpha, dev, staging, real)',
      });
    },
    async function handler(args) {
      const appEnv = args.e || args.env || 'dev';

      const parsedEnv = await parseDotenv(appEnv); // dotenv 파싱
      writeEnv(parsedEnv); // 환경 변수 스크립트 파일 생성
      await copyEnv(appEnv); // .env 파일 복사

      return parsedEnv;
    },
  )
  .parse();
"env:dev": "node dotenv.rollup.mjs next-env --env=${APP_ENV:-dev} && next dev",
"env:start": "node dotenv.rollup.mjs next-env -e ${APP_ENV:-dev} && next start"

 

빙빙돌아가기 싫으면

+ Recent posts