Unable to designate NODE_ENV as production by utilizing npm and webpack

I'm encountering an issue while trying to access process.env.NODE_ENV within my application. Whenever I check it, I only receive the error message process is not defined.

package.json:

"scripts": {
    "dev": "node ./node_modules/webpack/bin/webpack.js",
    "prod": "NODE_ENV=production node ./node_modules/webpack/bin/webpack.js -p"
},

webpack.config.js:

const NODE_ENV = process.env.NODE_ENV ? process.env.NODE_ENV.toLowerCase() : 'development';

and below :

plugins: [
  new webpack.DefinePlugin({
    'process.env': {
      'NODE_ENV': JSON.stringify(NODE_ENV),
      'URL_DEV': JSON.stringify("specificIP"),
      'URL_PROD': JSON.stringify("OtherIP")
    }
  })
]

Within the source code of the app:

switch (process.env.NODE_ENV) {
  case 'development':
    url = process.env.URL_DEV;
    break;
  case 'production':
    url = process.env.URL_PROD;
    break;
  default:
    url = process.env.URL_DEV;
}

Despite implementing these changes, I am still facing the issue with process being undefined. Can anyone point out what mistake I might be making in this setup?

Answer №1

It appears that the issue may have stemmed from the scripts section in my package.json file, as now the NODE_ENV is correctly configured when using the following:

"scripts": {
  "dev": "cross-env NODE_ENV=development node ./node_modules/webpack/bin/webpack.js --progress --colors --bail",
  "prod": "cross-env NODE_ENV=production webpack -p --progress --colors --bail"
}

I ended up utilizing cross-env and surprisingly, it resolved the issue. If you find yourself running out of solutions like I did, it might be worth giving this a try.

Answer №2

When NODE_ENV is passed as shown, a trailing space is included.

"compile": "NODE_ENV=development node ./node_modules/webpack/bin/webpack.js -w",

To avoid this, trim the value beforehand:

process.env.NODE_ENV.trim()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on transitioning from Bower to NPM or Yarn in a .Net Core 2.0 MVC project

In my .NET Core MVC project, I have utilized Bower to handle Bootstrap, jQuery, and other libraries. With the news of Bower discontinuing its services, how can I smoothly transition these dependencies to NPM or Yarn/Webpack as recommended by the Bower te ...

Create a randomly generated value in a JSON format

{ "description": "AppName", "name": "appName", "partnerProfile": { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f19090b1969c90989ddf929e9c">[email protected]</a>", "firstName": "John", ...

Mocha: A Unique Perspective on Testing the express.Router Instance

As I was developing a JavaScript controller file, I came across the need to test if my controller instance contains an instance of the express method called Router(). import {assert} from 'chai'; import {UF_Controller} from '../../controlle ...

What is the best way to retrieve a selected value from one dropdown list and populate it into another dropdown

Can someone assist me with retrieving the selected answer from one drop-down list and populating it into another drop-down list? Below is my code for programming groups A and B: Example: If a user selects an option from group A and group B, I would li ...

Executing the executeScript method in Microsoft Edge using Java and WebDriverWould you like a different version?

I'm currently attempting to execute the following code in Microsoft Edge using WebDriver ExpectedCondition<Boolean> jsLoad = driver -> ((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equals(&quo ...

Encode data in JSON format using Javascript and then decode it using PHP

In my coding journey, I decided to create an object using Javascript to pass it as an argument to a PHP script. var pattern = new Object(); pattern['@id'] = ''; pattern['@num'] = ''; pattern.cprop = new Object(); // ...

Generate random div elements and insert them dynamically into a fixed-sized container using AngularJS. The number of div elements created can range anywhere from 0 to

Within a div of fixed size, dynamically generated div elements are displayed using ng-repeat. The inner divs should adjust their size to accommodate the number of child divs present - for example, if only one div is present, it should take up 100% of the s ...

Unable to serve static files when using NextJs in conjunction with Storybook

The documentation for Next.js (found here) suggests placing image file paths under the public directory. I have a component that successfully displays an image in my Next.js project, but it doesn't render properly within Storybook. The image file is ...

AngularJS does not update values properly if there is a style applied to the parent container

I'm struggling to find the best approach to handle this situation. This is how my AngularJS code looks: <span class="something" ng-hide="onsomecondition"> {{value}} </span> .something{ text-align:left; padding:10px;} Issue: The value ...

Scanner (IE5) impact on page load speeds

I have developed an MVC project which is designed as a single-page application (SPA) utilizing knockoutjs and sammy frameworks. The following script is placed in the head section of the page: <script> var startTime = (new Date()).getTime(); </ ...

Using the `ssh2` module in Node.js without specifying a specific object

When you use require('ssh2') in Node.js without a specific object (e.g. require('ssh2').Client), what does it imply? I'm in the process of understanding some code and still new to learning Node.js. Here's how it is being used: ...

Error message: npm command not recognized while running commands within an Electron application

While developing an electron app, I utilize shell commands with child_process.exec. One of the commands I use is npm run start, which functions perfectly in a development environment. However, upon building the application for production, all npm commands ...

Verify whether a div element is styled in a specific manner

Upon initial load of my website, if the page is maximized or in fullscreen mode, the comBrand div will have specific CSS properties applied. However, during a resize event, I use the .css() function to adjust the properties of this element so it doesn&apos ...

Vue JS: Easily Calculate the Total Sum of All Columns

An example of a query in the backend controller public function show($id) { $structural = DB::table('attendance')->where('payroll_daily_id',$id) ->where('assignment','STRUCTURAL') -&g ...

Having trouble displaying the Primevue dialog modal in Vue 3?

I am using [email protected] and [email protected] Main script import { createApp } from 'vue' import App from './App.vue' import router from './router' import PrimeVue from 'primevue/config'; import &apos ...

We are encountering an issue with a missing module: Error: Unable to locate '@angular/flex-layout' in the 'app' directory

Out of nowhere I encountered the following error: Module not found: Error: Can't resolve '@angular/flex-layout' in '\src\app' This issue popped up right after I installed @angular/cdk. To address this error, I reinstal ...

Typeahead.js is a powerful tool offered by Twitter that allows for easy auto-completion

I am currently working on a program that has the capability to search for specific university courses based on certain parameters. Within my large JSON object, there are 1360 objects, each consisting of around 20-30 parameters. However, I am only intereste ...

Executing VueJS keyup handler after the previous onclick handler has been executed

Link to example code demonstrating the issue https://codepen.io/user123/pen/example-demo I am currently facing an issue with a text field named search_val that has a watcher attached to it. The text field includes a v-on keyup attribute to detect when th ...

jQuery fieldset.change is a feature that allows you to manipulate

I'm looking to update the value of a button when a radio button is clicked. <fieldset id="product-color"> <input type="radio" id="red" name="color" value="Red"> <label for="red">Red</label><br> <input typ ...

Error message in Angular js: Unable to load file using XMLHttpRequest

Encountering an error while debugging an Angular JS application in the WebStorm IDE. The error message states: "XMLHttpRequest cannot load file:///C:/Users/../list.html. Cross origin requests are only supported for HTTP." Provided Javascript code : var a ...