From 6e65255c9e724d89156b93b7b5b38107d96cf037 Mon Sep 17 00:00:00 2001 From: Robbo-lab Date: Wed, 16 Oct 2024 15:17:43 +0800 Subject: [PATCH] feat: environment --- .gitignore | 3 ++- package-lock.json | 12 ++++++++++++ package.json | 1 + webpack.config.js | 17 ++++++++++++++--- 4 files changed, 29 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index 8af0b1a..ae2cda6 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -*node_modules/* \ No newline at end of file +*node_modules/* +.env \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index a8bf8c7..e11eea5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,6 +12,7 @@ "bulma": "^1.0.2", "copy-webpack-plugin": "^12.0.2", "css-loader": "^7.1.2", + "dotenv": "^16.4.5", "react": "^18.3.1", "react-dom": "^18.3.1", "react-router-dom": "^6.27.0", @@ -3061,6 +3062,17 @@ "tslib": "^2.0.3" } }, + "node_modules/dotenv": { + "version": "16.4.5", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.5.tgz", + "integrity": "sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, "node_modules/ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", diff --git a/package.json b/package.json index 00c2d90..5b20edf 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,7 @@ "bulma": "^1.0.2", "copy-webpack-plugin": "^12.0.2", "css-loader": "^7.1.2", + "dotenv": "^16.4.5", "react": "^18.3.1", "react-dom": "^18.3.1", "react-router-dom": "^6.27.0", diff --git a/webpack.config.js b/webpack.config.js index 7cf041b..e6d65e9 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -1,20 +1,30 @@ const path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); +const { DefinePlugin } = require("webpack"); +const dotenv = require("dotenv"); + +// Load environment variables from .env file into process.env +const env = dotenv.config().parsed || {}; + +// Convert the env variables to a format DefinePlugin can understand +const envKeys = Object.keys(env).reduce((prev, next) => { + prev[`process.env.${next}`] = JSON.stringify(env[next]); + return prev; +}, {}); module.exports = { entry: "./src/index.js", output: { filename: "bundle.js", path: path.resolve(__dirname, "dist"), + clean: true, // Ensures dist/ is cleaned on each build }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, - use: { - loader: "babel-loader", - }, + use: "babel-loader", }, { test: /\.css$/, @@ -26,6 +36,7 @@ module.exports = { new HtmlWebpackPlugin({ template: "./public/index.html", }), + new DefinePlugin(envKeys), // Inject environment variables into the bundle ], devServer: { static: {