将非NODE_ENV变量从gulpfile传递到其他js文件

时间:2018-02-10 09:28:33

标签: javascript node.js gulp

我是否可以从NODE_ENV其他gulpfile.js文件中传递一些 javascript变量?

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(/* ... */)
}

为什么我不使用NODE_ENV是必须从控制台更改它的值。

另外,我总是使用webpack并在gulpfile.js内配置它,所以也许某些webpack插件可以实现......

2 个答案:

答案 0 :(得分:2)

如果您不关心全局命名空间中的冲突

// gulpfile.js
global.isDevelopment = true;

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

或者您可以创建一些配置模块

// 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;

然后在gulpfile.js

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

myEnv.set('isDevelopment', true)

和somejsfile.js

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

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

或类似的东西,带字符串键的getter不是我的最佳解决方案,但这里的想法是使用一些带有本地存储的共享模块。

答案 1 :(得分:1)

如果要使用webpackDefine插件可以执行此操作:

plugins: [
    new webpack.DefinePlugin({
        IS_DEVELOPMENT: isDevelopment
    })
]
相关问题