I am trying to set the environment variable NODE_ENV for my project.
I am using Windows and have set the NODE_ENV in the system settings - this has been verified by typing SET and identifying for the row below in the output.
NODE_ENV=production
I cannot seem to get the variable to set in webpack though.
When adding the code below to my project (index.js) it only logs out undefined
console.log('PROCESS', process.env.NODE_ENV)
My webpack config:
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
process.env.NODE_ENV = process.env.NODE_ENV || 'development'
if (process.env.NODE_ENV === 'test') {
require('dotenv').config({ path: '.env.test' })
} else if (process.env.NODE_ENV === 'development') {
require('dotenv').config({ path: '.env.development' })
} else if (process.env.NODE_ENV === 'production') {
require('dotenv').config({ path: '.env.production' })
} else {
require('dotenv').config({ path: '.env.development' })
}
module.exports = (env) => {
const isProduction = env === 'production';
...
plugins: [
CSSExtract,
new UglifyJSPlugin(),
new webpack.DefinePlugin({
'process.env.FIREBASE_API_KEY': JSON.stringify(process.env.FIREBASE_API_KEY),
'process.env.FIREBASE_AUTH_DOMAIN': JSON.stringify(process.env.FIREBASE_AUTH_DOMAIN),
'process.env.FIREBASE_DATABASE_URL': JSON.stringify(process.env.FIREBASE_DATABASE_URL),
...
}),
devtool: isProduction ? 'source-map' : 'inline-source-map',
...
I have read this question, but still cannot get the env variable to set.
Where am I going wrong?
I managed to get set the NODE_ENV by using the cross-env package!
If you are developing node.js on Windows this can be very useful. Linux/Mac users would not have this problem.
To set the environment variable simply type
cross-env NODE_ENV=production [your commend goes here]
Example:
cross-env NODE_ENV=production webpack --env production
Related
I have this given module in config.js. I want to include this is my index.js. I tried multiple ways but config variable is always undefined.
I tried like this.
const config = require('./config') //undefined
const config = require('./config')("dev") //error
const config = require('./config')["dev"] // error
const config = require('./config').get("dev")
Here is how i run it
// my command.
npm run start:dev
"scripts": {
"start:prod": "set NODE_ENV=prod pm2 start index.js --watch",
"start:dev": "set NODE_ENV=dev && node index.js"
},
Here is module
let env = process.env.NODE_ENV;
require('dotenv').config();
const dev = {
app: {
port: parseInt(process.env.DEV_APP_PORT) || 3000
},
db: {
host: process.env.DEV_DB_HOST || 'localhost',
port: parseInt(process.env.DEV_DB_PORT) || 27017,
name: process.env.DEV_DB_NAME || 'myDB',
},
imagePath: "./profileImages/",
LogFillePath: "logs/combined.log",
ErrorFilePaht: "logs/error.log",
JwtSecret: process.env.JWT_SECRET
};
const prod = {
app: {
port: parseInt(process.env.PROD_APP_PORT) || 9000
},
db: {
host: process.env.PROD_DB_HOST || 'localhost',
port: parseInt(process.env.PROD_DB_PORT) || 27017,
name: process.env.PROD_DB_NAME || 'myDB'
},
imagePath: "./profileImages/",
LogFillePath: "logs/combined.log",
ErrorFilePaht: "logs/error.log",
JwtSecret: process.env.JWT_SECRET
};
const config = {
dev,
prod
};
module.exports = config[env];
I have this given module in config.js. I want to include this is my index.js. I tried multiple ways but config variable is always undefined.
I tried like this.
Try something like this for your config.js:
require("dotenv").config();
const dev = {
// ...
};
const prod = {
// ...
};
const configs = {
dev,
prod,
};
const config = configs[process.env.NODE_ENV];
if (!config) throw new Error("No valid configuration found, ensure your NODE_ENV is properly set");
module.exports = config;
Then you can simply
const config = require('./config');
I have a script in nodejs with webpack where I want to use environment variables from docker-compose but every times the variables is undefined.
this is a little piece of docker-compose:
container:
image: "node:8-alpine"
user: "node"
working_dir: /home/node/app
environment:
- NODE_ENV=development
volumes:
- ./project:/home/node/app
- ./conf:/home/node/conf
command: "yarn start"
I have this webpack configuration:
const path = require('path');
const TerserPlugin = require('terser-webpack-plugin');
const DefinePlugin = require('webpack').DefinePlugin;
module.exports = {
entry: './src-js/widget.js',
mode: process.env.NODE_ENV || 'development',
output: {
filename: 'widget.js',
path: path.resolve(__dirname, 'public')
},
optimization: {
minimizer: [new TerserPlugin()]
},
plugins: [
new DefinePlugin({
ENV: JSON.stringify(process.env.NODE_ENV)
})
]
};
Into my node script I would like to use NODE_ENV variables, so I have tried all this solutions but every time is undefined
console.log(process.env.NODE_ENV);
console.log(ENV);
console.log(process.env); //is empty
From the docker container I have tried to print environment variables and inside it there is NODE_ENV but I can't use it into node file. Why?
Usually I use yarn build or yarn watch to recompile it
Try this in your webpack configuration:
new DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})
Additionally, official docs have a snippet about it.
In my index.js code, I've checked the value of process.env.NODE_ENV variable and expected it to be 'production', but on Heroku this variable is registering a value of 'development'.
I've read that Heroku sets this value to 'production' by default, but for some reason it's still registering as 'development', even when I explicitly set the value under Config Vars it still shows it's development. Below is the condition in my index.js file:
if (process.env.NODE_ENV === 'production') {
// serve production assets...
} else {
// serve development assets...
}
If I change the line to...
if (process.env.NODE_ENV === 'development') {
The production assets get served up just fine on Heroku.
Any ideas on how I may get process.env.NODE_ENV to register as 'production' on Heroku?
EDIT:
Within my webpack.js file I am doing this...
const env = process.env.NODE_ENV;
const config = {
mode: env || 'development'
};
module.exports = {
// some code...
...config, // 'development' or 'production' mode
// more code...
}
I did try hard-coding this value to 'production' like so...
mode: env || 'production'
But that had no effect.
To check if the NODE_ENV variable is set you can open a console in your project enviroment at:
https://dashboard.heroku.com/apps/{{your-app-name}}?web-console={{your-app-name}}
Then run node to execute node code from console (you can run this command in your local repo too):
heroku run node
Once node is running in terminal execute:
console.log(process.env.NODE_ENV) // production
It should return the enviroment variable value of the project
The problem is with my webpack.js file, specifically this code:
const env = process.env.NODE_ENV;
const config = {
mode: env || 'development'
};
For some reason process.env.NODE_ENV was being set to "development". I've deleted the config variable and replaced it with this hard-coded value:
mode: 'development'
And now it works. Only problem is I must manually change that value before I deploy to production.
I am using gulp in my reactjs solution and want to set the NODE_ENV, I tried this:
gulp.task('set-dev-node-env', function() {
return process.env.NODE_ENV = 'development';
});
//dev environment run
gulp.task('default', ['set-dev-node-env', 'webpack-dev-server']);
When I run gulp and check the chromeconsole it says:
testing process.env.NODE_ENV undefined
What am I missing or how can I set this NODE_ENV variable? I would like to set it in the gulpfile somehow.
Here is the complete project: github
Since you are using WebPack you can use the WebPack Define Plugin to inject the NODE_ENV
For example in your webpack.config.dev.js:
module.exports = {
...
plugins: [
...
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development'),
}),
],
};
Then in your react code you will have access to it NODE_ENV you set as process.env.NODE_ENV.
You can try this using gulp-env module
// gulpfile.js
var gulp = require('gulp');
var env = require('gulp-env');
gulp.task('set-dev-node-env', function () {
env({
vars: {
NODE_ENV: "development"
}
})
});
gulp.task('default', ['set-dev-node-env', 'webpack-dev-server'])
I have a gulpfile, where I create a webpackDevServer to live-update my js code. I set a process.env.NODE_ENV variable in gulpfile, but for some reason webpack doesn't see it - it is undefined.
Here's the relevant piece of my gulpfile.js:
gulp.task("watch", ["_set-env:dev"], function() {
// modify default webpack configuration for Development Server
var webpackDevConfig = Object.create(webpackConfig);
webpackDevConfig.devtool = "eval";
webpackDevConfig.debug = "true";
new webpackDevServer(webpack(webpackDevConfig), {
proxy: {
"/api/*": {target: "http://localhost:8000", secure: false},
"/static/*": {target: "http://localhost:8000", secure: false},
"/media/*": {target: "http://localhost:8000", secure: false}
}
}).listen(8001, "localhost", function (err) {
if (err) throw new gutil.PluginError("webpack-dev-server", err);
gutil.log("[webpack-dev-server]", "http://localhost:8001" + webpackDevConfig.output.publicPath);
});
});
gulp.task("_set-env:dev", function() {
gutil.log("set-env", "ENV => development");
genv({
vars: {
NODE_ENV: "development"
}
});
});
Then in webpack I check its value and it is undefined:
const webpack = require("webpack");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
...
const environmentsFile = path.join(__dirname, "/environments.json");
const nodeModulesPath = path.join(__dirname, "/node_modules");
const bowerComponentsPath = path.join(__dirname, "/bower_components");
console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
console.log(process.env.NODE_ENV);
const webpackConfig = {
entry: {
app: ["app.js"]
},
And on the console I see:
$ gulp watch
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
undefined
[22:28:34] Using gulpfile ~/Documents/frontend/gulpfile.js
[22:28:34] Starting '_set-env:dev'...
[22:28:34] set-env ENV => development
[22:28:34] Finished '_set-env:dev' after 7.63 ms
[22:28:34] Starting 'watch'...
You probably have something like this close to the top of your gulpfile:
var webpackConfig = require('./webpack.config.js');
That means your webpack configuration is evaluated before the _set-env:dev task even runs. Remember: your gulpfile only defines tasks. The tasks themselves aren't run until after the entire gulpfile has been evaluated.
You need to defer requiring your webpack configuration until after the _set-env:dev task has run by deleting the line at the top of your gulpfile and putting the require() directly into your watch task:
gulp.task("watch", ["_set-env:dev"], function() {
// modify default webpack configuration for Development Server
var webpackDevConfig = Object.create(require('./webpack.config.js'));