Skip to content

Commit

Permalink
refactor: 💡 .env change to production default env file
Browse files Browse the repository at this point in the history
BREAKING CHANGE: 🧨 .env change to production default env file, keep docker .env compatible,
and follow dotenv recommended @link
https://github.com/motdotla/dotenv#should-i-have-multiple-env-files
  • Loading branch information
SolidZORO committed Jun 8, 2020
1 parent 81f6f1f commit dcca7d0
Show file tree
Hide file tree
Showing 6 changed files with 95 additions and 47 deletions.
11 changes: 7 additions & 4 deletions packages/leaa-api/src/modules/v1/config/config.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@ import { Module, Global } from '@nestjs/common';

import { ConfigService } from '@leaa/api/src/modules/v1/config/config.service';

const __PROD__ = process.env.NODE_ENV === 'production';
const envFilePath = path.resolve(__PROD__ ? '.env.production' : '.env');

console.log('\n\n🌈 .env File Path:', envFilePath, '\n\n');
// Keep docker .env compatible, and follow dotenv recommended
// @link https://github.com/motdotla/dotenv#should-i-have-multiple-env-files
let envFileName = `.env.${process.env.NODE_ENV}`;
if (process.env.NODE_ENV === 'production') envFileName = '.env';

const envFilePath = path.resolve(envFileName);
export const envConfig = new ConfigService(envFilePath);

console.log('\n\n🌈 Load .env File of API:', envFilePath, '\n\n');

@Global()
@Module({
providers: [
Expand Down
2 changes: 2 additions & 0 deletions packages/leaa-dashboard/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
# PROD **00
# DEV **07

__ENV__=prod

# PROJECT
SITE_NAME=Leaa
API_URL=http://localhost:5000
Expand Down
52 changes: 44 additions & 8 deletions packages/leaa-dashboard/tools/webpack/_const.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,49 @@
/* eslint-disable no-underscore-dangle, max-len */
const path = require('path');
const dotenv = require('dotenv');
const ip = require('ip');
const fs = require('fs');

const WPCONST = {};
const ROOT_DIR = path.resolve(__dirname, '../../');
const __DEV__ = process.env.NODE_ENV !== 'production';

// ENV
if (WPCONST.IS_ANALYZER) {
console.log('\n\n👏👏👏👏 ANALYZER \n\n');
const ENV_FILE_NAME = process.env.NODE_ENV === 'production' ? '.env' : `.env.${process.env.NODE_ENV}`;

function getEnvFilePath() {
const envFilePath = `${ROOT_DIR}/${ENV_FILE_NAME}`;

if (!fs.existsSync(envFilePath)) {
console.log('\n');
console.log(''.padStart(48, '='));
console.error(`\n🔰 Please create \`${ENV_FILE_NAME}\` file first\n`);
console.log(''.padStart(48, '='));
console.log('\n\n');

process.exit(-1);
}

return envFilePath;
}

WPCONST.__DEV__ = !process.argv.includes('--release');
WPCONST.__PROD__ = process.argv.includes('--release');
const ENV_FILE_PATH = getEnvFilePath();

function getEnvData() {
const env = dotenv.config({ path: ENV_FILE_PATH }).parsed;

// DEV, Change API_URL to IP Address
if (__DEV__) env.API_URL = env.API_URL.replace('localhost', ip.address());

return env || {};
}

const WPCONST = getEnvData();

WPCONST.__DEV__ = __DEV__;
WPCONST.__PROD__ = !__DEV__;

WPCONST.ENV_FILE_NAME = ENV_FILE_NAME;
WPCONST.ENV_FILE_PATH = ENV_FILE_PATH;

WPCONST.IS_SERVER = process.argv.includes('--server');
WPCONST.IS_VERBOSE = process.argv.includes('--verbose');
WPCONST.IS_SMP = process.argv.includes('--smp');
Expand All @@ -20,6 +54,8 @@ WPCONST.IS_ANALYZER =
process.argv.includes('-vvv');
WPCONST.IS_DEBUG = process.argv.includes('--debug');

if (WPCONST.IS_ANALYZER) console.log('\n\n👏👏👏👏 ANALYZER \n\n');

WPCONST.DEV_PREFIX = WPCONST.__DEV__ ? '____' : '';
WPCONST.CHUNK_HASH = WPCONST.__DEV__ ? '-DEV' : '_[chunkhash:4]';
WPCONST.STYLE_CHUNK_HASH = WPCONST.__DEV__ ? '_DEV' : '_[contenthash:4]';
Expand All @@ -31,7 +67,7 @@ WPCONST.DEVTOOL = WPCONST.__DEV__ && WPCONST.IS_DEBUG ? 'eval-source-map' : fals

//
// DIR PATH
WPCONST.ROOT_DIR = path.resolve(__dirname, '../../');
WPCONST.ROOT_DIR = ROOT_DIR;
WPCONST.SRC_DIR = path.resolve(`${WPCONST.ROOT_DIR}/src`);
WPCONST.PUBLIC_DIR = path.resolve(`${WPCONST.ROOT_DIR}/public`);
WPCONST.NODEMODULES_DIR = path.resolve(`${WPCONST.ROOT_DIR}/node_modules`);
Expand Down Expand Up @@ -75,4 +111,4 @@ WPCONST.REGX_FONT = /\.(woff2|woff|ttf|eot)$/;
// eslint-disable-next-line no-underscore-dangle
WPCONST.PACKAGE_FILE = path.resolve(`${WPCONST.ROOT_DIR}/package.json`);

module.exports = { WPCONST };
module.exports = { WPCONST, getEnvData };
4 changes: 2 additions & 2 deletions packages/leaa-dashboard/tools/webpack/_devServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ const { stats } = require('./_stats');
module.exports = {
devServer: {
contentBase: WPCONST.BUILD_DIR,
https: Boolean(`${process.env.SERVER_PROTOCOL}` === 'https'),
port: process.env.SERVER_PORT,
https: Boolean(`${WPCONST.SERVER_PROTOCOL}` === 'https'),
port: Number(WPCONST.SERVER_PORT),
hot: true,
// inline: true,
// Specify what bundle information gets displayed
Expand Down
46 changes: 19 additions & 27 deletions packages/leaa-dashboard/tools/webpack/_fn.js
Original file line number Diff line number Diff line change
@@ -1,44 +1,36 @@
const dotenv = require('dotenv');
/* eslint-disable no-underscore-dangle */

const ip = require('ip');
const childProcess = require('child_process');

const { WPCONST } = require('./_const');
const { getVersion } = require('../cli/get-build-info');

function getEnvInfo() {
const envPath = `${WPCONST.ROOT_DIR}/${WPCONST.__DEV__ ? '.env' : '.env.production'}`;
const env = dotenv.config({ path: envPath }).parsed;

// DEV, Change API_URL to IP Address
if (WPCONST.__DEV__) env.API_URL = env.API_URL.replace('localhost', ip.address());

return env;
}

const env = getEnvInfo();
const getGitVersion = (childProcess.execSync('git rev-parse HEAD') || '').toString().substr(0, 4);
const getVersion = `v${process.env.npm_package_version} (${getGitVersion})`;

function showEnvInfo() {
// emoji for CLI
const serverBaseByText = `${env.SERVER_PROTOCOL}://${ip.address() || env.SERVER_HOST}:${env.SERVER_PORT}`;
const serverBaseByText = `${WPCONST.SERVER_PROTOCOL}://${ip.address() || WPCONST.SERVER_HOST}:${WPCONST.SERVER_PORT}`;
const serverBaseByEmoji = `✨✨ \x1b[00;45;9m${serverBaseByText}\x1b[0m ✨✨`;
const serverEnv = `${env.NODE_ENV !== 'production' ? '🚀' : '🔰'} ${(env.NODE_ENV || 'NOT-ENV').toUpperCase()}`;
const serverEnv = `${WPCONST.__DEV__ ? '🚀' : '🔰'} ${(WPCONST.__ENV__ || 'NOT-ENV').toUpperCase()}`;

console.log(
`\n\n\n\n> 🌈 DEBUG ${env.DEBUG_MODE === 'true' ? '✅' : '➖'} / DEMO ${env.DEMO_MODE === 'true' ? '✅' : '➖'}`,
`\n\n\n\n> 🌈 DEBUG ${WPCONST.DEBUG_MODE === 'true' ? '✅' : '⛔️'} / DEMO ${
WPCONST.DEMO_MODE === 'true' ? '✅' : '⛔'
} / ${WPCONST.__ENV__} / ${WPCONST.ENV_FILE_NAME}`,
);

console.log(`\n\n> ${serverEnv} / URL ${serverBaseByEmoji}`);
console.log(`\n> ${serverEnv} / URL ${serverBaseByEmoji}`);

console.log('\n> 📮 ENVDATA');
console.log(' - NAME ', `${env.SITE_NAME}`);
console.log(' - VERSION ', getVersion);
console.log('');
console.log(' - API_URL ', `${env.API_URL}`);
console.log('\n> 📮 ENVINFO');
console.log(' - NAME ', `${WPCONST.SITE_NAME} ${getVersion}`);
console.log(' - API ', `${WPCONST.API_URL}`);
console.log('');
console.log(' - DEV_PREFIX ', `${WPCONST.DEV_PREFIX}`);
console.log(' - CHUNK_HASH ', `${WPCONST.CHUNK_HASH}`);
console.log(' - PUBLIC_DIR ', `${WPCONST.PUBLIC_DIR}`);
console.log(' - BUILD_DIR ', `${WPCONST.BUILD_DIR}`);
console.log(' - PREFIX ', `${WPCONST.DEV_PREFIX}`);
console.log(' - CHUNK ', `${WPCONST.CHUNK_HASH}`);
console.log(' - PUBLIC_DIR ', `${WPCONST.PUBLIC_DIR}`);
console.log(' - BUILD_DIR ', `${WPCONST.BUILD_DIR}`);
console.log('\n\n\n');
}

module.exports = { showEnvInfo, getVersion, getEnvInfo };
module.exports = { showEnvInfo, getVersion };
27 changes: 21 additions & 6 deletions packages/leaa-dashboard/tools/webpack/_plugins.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,11 @@ const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
// const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');

const { showEnvInfo, getEnvInfo } = require('./_fn');
const { showEnvInfo } = require('./_fn');
const { WPCONST } = require('./_const');
const { analyzer } = require('./_analyzer');
const { provide } = require('./_provide');

const env = getEnvInfo();

class ShowEnvInfoWebpackPlugin {
apply(compiler) {
compiler.hooks.done.tap('ShowEnvInfoWebpackPlugin', () => showEnvInfo());
Expand All @@ -29,16 +27,33 @@ class ShowEnvInfoWebpackPlugin {

// HtmlWebpackPlugin
const htmlWebpackPluginOption = {
__ENV_DATA__: Buffer.from(JSON.stringify(_.pick(env, Object.keys(env)))).toString('base64'),
__ENV_DATA__: Buffer.from(
JSON.stringify(
_.pick(WPCONST, [
'SITE_NAME',
'API_URL',
'API_VERSION',
'ANALYTICS_CODE',
//
'DEMO_MODE',
'DEBUG_MODE',
//
'SERVER_PROTOCOL',
'SERVER_PORT',
'SERVER_HOST',
]),
),
).toString('base64'),
__BUILD_DATA__: Buffer.from(
JSON.stringify({
BUILDTIME: moment().format('YYYYMMDD-HHmmss'),
VERSION: `v${process.env.npm_package_version}`,
MODE: WPCONST.MODE,
}),
).toString('base64'),
__ANALYTICS_CODE__: (!WPCONST.__DEV__ && env && env.ANALYTICS_CODE && `<script>${env.ANALYTICS_CODE}</script>`) || '',
title: `${env.SITE_NAME || '-'}`,
__ANALYTICS_CODE__:
(!WPCONST.__DEV__ && WPCONST && WPCONST.ANALYTICS_CODE && `<script>${WPCONST.ANALYTICS_CODE}</script>`) || '',
title: `${WPCONST.SITE_NAME || '-'}`,
manifest: `${WPCONST.CDN_DIR_PATH}/manifest.json`,
filename: `${WPCONST.BUILD_DIR}/index.html`,
template: `${WPCONST.VIEWS_DIR}/index.ejs`,
Expand Down

0 comments on commit dcca7d0

Please sign in to comment.