How can I set NODE_ENV? - node.js

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'])

Related

Node.js - NODE_ENV is undefined

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

How to pass process.env.NODE_ENV from Gulp to Webpack?

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'));

Gulp-nodemon and watch task

I'm trying to create my build flow using gulp and nodemon. The objective is to watch sass files and compile them to css, and also restart node application when server file changes.
My gulpfile.js:
gulp.task('sass', function(){
return gulp.src(sassFilesTobeProcessed).
pipe(sass()).
pipe(concat('ready_stylesheet.css')).
pipe(gulp.dest('express/public/stylesheets'))
})
gulp.task('watch', function(){
return gulp.watch(allSassFiles, ['sass']);
})
gulp.task('serve', function(){
return nodemon({
script: 'express/app.js',
}).on('start', ['watch'])
.on('change', ['watch'])
.on('restart', function(){
console.log('restarted');
})
})
The watch task is working fine, files are compiled after change. But changes in my app.js server file doesn't trigger server restart. When I comment the .on statements it starts to work fine (server reloads), but then of course sass files are no longer observed. I assume hence, there is some conflict between these two, which I cannot discover. Appreciate any help! My OS - Windows 7, node 4.2.6, nodemon 1.9.1
Use a task dependency instead of .on(event) to start your watch task:
gulp.task('serve', ['watch'], function(){
return nodemon({
script: 'express/app.js',
})
.on('restart', function(){
console.log('restarted');
})
})
emit the restart event with nodemon
const cfg = require('../config')
const gulp = require('gulp')
const nodemon = require('nodemon')
const gnodemon = require('gulp-nodemon')
gulp.task('nodemon', ['ts', 'json'], () => {
gnodemon({
script: cfg.paths.main,
tasks: ['ts', 'json'],
ext: 'js',
watch: [cfg.paths.src],
// para no alterar el entorno de prodicion con test
env: {'NODE_ENV': process.env.NODE_ENV !== 'production'
? process.env.NODE_ENV || 'development' : 'development'}
})
.on('start', ['mocha'])
})
gulp.task('default', ['nodemon'], () => {
gulp.watch(cfg.paths.src, (event) => nodemon.emit('restart'))
})

Accessing NODE_ENV at runtime in the server.js configuration of Sails.js

I find myself not able to access the NODE_ENV variable when trying to make config changes in the config/server.js file of Sails.js. I want to configure the serverOptions flag of the express property and bind ssl certificates - but only for production.
Assuming I started the server with node app.js --prod
This doesn't work:
module.exports = { ... };
console.log(process.env.NODE_ENV); // undefined
But this does work:
module.exports = { ... };
setTimeout(function () {
console.log(process.env.NODE_ENV); // production
}, 1000);
Basically all I want to do is:
module.exports = (function () {
var env = process.env.NODE_ENV,
ret = { express: {} };
if (env == 'production') {
ret.express.serverOptions = { key: ..., cert: ... };
}
return ret;
}());
I've seen similar answers like https://stackoverflow.com/a/21152780/986408 but I can't understand how they should work when mine doesn't.
run your application like this instead:
NODE_ENV=production node app.js
or
sails lift --prod
in the application root directory. the command line switch you're trying to use is meant to be passed to the sails executable, not directly to your application javascript.

RequireJs Module in node always returns undefined when using in a grunt task

I've a small config file that I need in frontend and in my grunt task.
js/config.js:
define(function() {
return [
{
id: 'demo',
displayName: 'Demo'
}
];
});
I can load the file in frontend without problems it also work in node.
var requirejs = require('requirejs');
requirejs.config({
nodeRequire: require,
baseUrl: './js'
});
var config = requirejs('config')
But when I try to load the same file in a grunt task it returns undefined:
requirejs.config({
nodeRequire: require,
baseUrl: './js'
});
grunt.registerTask('lala', function () {
var config = requirejs('config')
});
The problem was that the I require requireJs outside of the module.exports function. So this works after all:
module.exports = function(grunt) {
var requirejs = require('requirejs');
requirejs.config({
nodeRequire: require,
baseUrl: './js/cfe/app/platforms/as'
});
grunt.registerTask('lala', function () {
var config = requirejs('config')
});
}
This code works for me. First I've installed requirejs:
cd /path/to/code/directory
npm install requirejs
Then in my app.js:
var requirejs = require('requirejs');
requirejs.config({
nodeRequire: require,
baseUrl: './js'
});
var config = requirejs('config');
console.log(config);
And in the js/config.js:
define(function() {
return [
{
id: 'demo',
displayName: 'Demo'
}
];
});
When I run it, I get the correct result:
$ node app.js
[ { id: 'demo', displayName: 'Demo' } ]
I'm using Node v0.10.1.

Resources