我可以将一些不是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 插件可以使之成为可能......
最佳答案
如果你不关心全局命名空间中的冲突
// 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 并不是最好的解决方案,但这里的想法是使用一些带有本地存储的共享模块。
关于javascript - 将非 NODE_ENV 变量从 gulpfile 传递到其他 js 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48719229/