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

标签 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 插件可以使之成为可能......

最佳答案

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

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

相关文章:

javascript - 在node js中过滤的json字符串

javascript - 如何使用 Node 一次安装多个 gulp 包?

javascript - Gulp watch 仅检测第一个更改

asp.net - 将脚手架网站发布到 azure

JavaScript - Canvas 绘图 - 脚本不起作用

javascript - Firebase 的云功能 : Headers Error When Trying To Read From Realtime Database

javascript - 将鼠标悬停在链接上时背景图像会发生变化,希望图像保留,直到悬停在其他链接上

node.js - "Cannot GET/"使用nodejs + laravel

javascript - 未处理的拒绝错误: Can't set headers after they are sent using Node

node.js - 缺少 A 的类型注释。A 是在函数类型中声明的类型参数