1

why process.env doesn't work in app.js file but works in webpack.config.js? I have my own webpack that I created myself. It was not created with CRA

the version so it is correct to deduce? Or is there any way to get it out? Or is it better not to drive at all? since it seems to me that this is also not correct, since the env file should be in the exception and on the server, when loading, probably nothing will be known about the version ...

I want to output the version to the console so I can see the webpack version. But I can't do it even though I made the necessary settings. if I output data in webpack, then everything works correctly if I output data in a simple js file, erroneous errors. in general, I want to make the version visible on the server after the build, and I want to do it in this way, you can simply output console.log, but this seems like the wrong solution console.log('ver 1.74.2')

enter image description here

enter image description here


import React from "react";
import styles from "./styles.scss";

const onClickEvent = (e) => {
  e.preventDefault();
  alert("You Clicked Me!");
};

const App = () => {
  console.log(process.env.TERM_PROGRAM_VERSION);
  return (
    <div className={styles.content}>
      <div className={styles.label}>OWN WEBPACK</div>
      <button className={styles.btn} onClick={onClickEvent}>
        Click Me 😎
      </button>
    </div>
  );
};

export default App;

const webpack = require("webpack");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

const production = process.env.NODE_ENV === "production";
const Dotenv = require("dotenv-webpack");
console.log(process.env.TERM_PROGRAM_VERSION);

module.exports = {
  entry: { myAppName: path.resolve(__dirname, "./src/index.js") },
  output: {
    path: path.resolve(__dirname, "./dist"),
    filename: production ? "[name].[contenthash].js" : "[name].js",
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ["babel-loader"],
      },
      {
        test: /\.s(a|c)ss$/,
        exclude: /node_modules/,
        use: [
          production ? MiniCssExtractPlugin.loader : "style-loader",
          {
            loader: "css-loader",
            options: {
              modules: true,
              sourceMap: !production,
            },
          },
          {
            loader: "sass-loader",
            options: {
              sourceMap: !production,
            },
          },
        ],
      },
    ],
  },
  resolve: {
    extensions: ["*", ".js", ".jsx", ".scss"],
  },
  plugins: [
    new CleanWebpackPlugin(),
    new Dotenv(),
    new webpack.HotModuleReplacementPlugin(),
    new HtmlWebpackPlugin({
      title: "Webpack & React",
      template: "./src/index.html",
      favicon: "./public/favicon.ico",
    }),
    new MiniCssExtractPlugin({
      filename: production ? "[name].[contenthash].css" : "[name].css",
    }),
    new webpack.DefinePlugin({
      "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV),
      "process.env.MY_ENV": JSON.stringify(process.env.MY_ENV),
    }),
  ],

  devServer: {
    port: 3001,
    hot: true,
  },
  mode: production ? "production" : "development",
};

  "scripts": {
    "start": "npm run build && node server/index.js",
    "dev": "NODE_ENV=development test=$TERM_PROGRAM_VERSION webpack serve --config webpack.config.js",
    "build": "NODE_ENV=production webpack --config webpack.config.js",
    "build:dev": "NODE_ENV=development webpack --config webpack.config.js",
    "build:watch": "NODE_ENV=development node ./node_modules/webpack/bin/webpack.js --config webpack.config.js --watch"
  },

//server/index.js
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();

if (process.env.NODE_ENV === 'development') {
    console.log('in development.');
} else {
    console.log('in production.');
}

/* App Config */
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, '../dist')));


/* Server Initialization */
app.get('/', (req, res) => res.sendFile('index.html'));
var port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Server initialized on: http://localhost:${port} // ${new Date()}`));

7
  • Does this answer your question? create react app not picking up .env files? Commented Jan 9, 2023 at 18:40
  • this answer is not suitable because I have my own webpack and not automatically generated Commented Jan 9, 2023 at 18:51
  • the solution for create react app is not suitable there. I have my own webpack from scratch Commented Jan 9, 2023 at 19:15
  • You should read up on what it does, it copies process.env variables from build time (webpack config) into a plain JS so you can access process.env available at runtime Commented Jan 10, 2023 at 14:28
  • so I won't be able to access this variable? console.log(process.env.TERM_PROGRAM_VERSION); Commented Jan 10, 2023 at 20:53

1 Answer 1

1

Change your env variable to REACT_APP_TERM_PROGRAM_VERSION then reload your app.

React env variables must start with REACT_APP_ prefix. See https://create-react-app.dev/docs/adding-custom-environment-variables/

Sign up to request clarification or add additional context in comments.

3 Comments

I have a webpack that I myself created from scratch
this answer is not suitable because I have my own webpack and not automatically generated
the answer suits you only for those who create a project using CRA. my project was completely assembled manually, so it does not fit here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.