Takeshi Tokugawa YD
Takeshi Tokugawa YD

Reputation: 913

Passing the non-NODE_ENV variables from gulpfile to other js-files

Can I pass some variable which is not NODE_ENV from the gulpfile.js tо other javascript file?

gulpfile.js

// Not related with NODE_ENV!
let isDevelopment = true;

somejsfile.js

/*
I need to get "isDevelopment" from the gulpfile.js...

For the production build, where no NodeJS avaliable, this condition will be
always "false". Maybe it's possible to delete it by webpack.
*/ 

if (isDevelopment) {  
    printDebugInfromation();
}

// No neccessirity to print it in the production build
function printDebugInfromation() {
    console.log(/* ... */)
}

Why I don't use NODE_ENV is necessity to change it value from console.

Also, I always use webpack and config it inside gulpfile.js, so maybe some webpack plugins make it possible...

Upvotes: 0

Views: 39

Answers (2)

Yurii
Yurii

Reputation: 126

if you don't care about collisions in global namespace

// gulpfile.js
global.isDevelopment = true;

// somejsfile.js
console.log(global.isDevelopment);

or you can create some configuration module

// my-evn.js module
const env = {};

module.exports = {
   set(key, value) {
      Object.assign(env, { [key]: value });
   },
   get(key) {
      return env[key];
   }
}
// or just like a global-like variable
module.exports = env;

then in gulpfile.js

const myEnv = require('./my-env.js');

myEnv.set('isDevelopment', true)

and in somejsfile.js

const myEnv = require('./my-env.js');

console.log(myEnv.get('isDevelopment'));

or something like this, getter with string keys isn't the best solution as for me, but the idea here to use some shared module with local storage.

Upvotes: 2

Takeshi Tokugawa YD
Takeshi Tokugawa YD

Reputation: 913

If to use webpack, Define plugin can do it:

plugins: [
    new webpack.DefinePlugin({
        IS_DEVELOPMENT: isDevelopment
    })
]

Upvotes: 1

Related Questions