[英]Is there a way to make Gulp skip or include JavaScript segments in different environments?
I'm porting some JavaScript from Jekyll to Gulp.我正在将一些 JavaScript 从 Jekyll 移植到 Gulp。
In Jekyll, I have a _config.yml file that includes environment variables like this:在 Jekyll 中,我有一个 _config.yml 文件,其中包含如下环境变量:
# _config.yml
app_url: https://app.mysite.com
dev_mode: true
dev_app_url: https://devapp.local
...and in the JS source, I can use Liquid to determine if I'm in dev_mode and modify what gets outputted eg: ...在 JS 源代码中,我可以使用 Liquid 来确定我是否处于 dev_mode 并修改输出的内容,例如:
// main.js
var appUrl = '{% if site.dev_mode %}{{ site.dev_app_url }}{% else %}{{ site.app_url }}{% endif %}';
{% if site.dev_mode %}
console.log(someVar);
//etc
{% endif %}
Is there a way to do similar things when using Gulp, so I can have different environment vars in my JS when I'm developing and have blocks of debugging code that will be omitted when I compile for production?有没有办法在使用 Gulp 时做类似的事情,这样我在开发时可以在我的 JS 中有不同的环境变量,并且在为生产编译时会省略调试代码块?
I think you should think about using nodejs environment variables.我认为您应该考虑使用 nodejs 环境变量。 Can be easily set on your package.json script definition if using npm.
如果使用 npm,可以在 package.json 脚本定义上轻松设置。 So you could end up with something similar to that:
所以你最终可能会得到类似的东西:
package.json: package.json:
{
"name": "whatever",
"version": "1.0.0",
"description": "",
"main": "index.js",
"directories": {
"lib": "lib"
},
"devDependencies": {
"gulp": "^4.0.2",
},
"scripts": {
"build": "export NODE_ENV=dev||set NODE_ENV=dev&& gulp build",
},
"repository": {
//...
}
}
And within your gulp build task (because that is where the node env was define in your package.json), you can now validate the nodejs env:在您的 gulp构建任务中(因为这是在 package.json 中定义节点环境的地方),您现在可以验证 nodejs 环境:
if (process.env.NODE_ENV == "dev")
{
//stuff()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.