如何将变量值从GULP注入到JS文件中 [英] How to inject variable value into JS file from GULP

查看:558
本文介绍了如何将变量值从GULP注入到JS文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望这是一个快速的问题。

我正在尝试做的是在用GULP构建文件的同时,将时间戳添加到JS文件中的Javascript对象中。基本上,在file.js中,我有一个对象,我希望拥有等于GULP构建时间的object.timeStamp。



我目前正在添加一个使用gulp-header到文件顶部的时间戳,但我被要求将时间戳添加到对象的一个​​属性中。



我的想法是注入来自GULP的价值,但到目前为止我发现的所有注入插件都是用于将一个文件的内容注入到目标文件中。



任何帮助都将不胜感激。 / p>

解决方案

您是否在使用任何模块? ES6模块,AMD,CommonJS,...?



如果是这样,您可以生成 config 模块你可以在哪里注入任何你想要的变量。它看起来像这样:



config.tmpl.js

  module.exports =<%= config%> 

config gulp任务

  var gulp = require('gulp'); 
var template = require('gulp-template');
var rename = require('gulp-rename');
$ b $ gulp.task('config',function(){
return gulp.src('path / to / config.tmpl.js')
.pipe(template( {config:JSON.stringify({
timeStamp:new Date()
})}))
.pipe(rename('config.js'))
.pipe gulp.dest('path / to / config.js'));
});

最后,在您的JS文件中

  var config = require('path / to / config.js'); 

var object = {
timeStamp:config.timeStamp
}


Hopefully this is a quick question.

What I'm trying to do is to add a timestamp into a Javascript object in a JS file while the file is being built with GULP. Basically, in "file.js", I have an object where I would like to have object.timeStamp that equals the time of the GULP build.

I am currently adding a timestamp to the top of the file using gulp-header, but I have been asked to add the timestamp to a property in the object.

My thought was to inject the value from GULP, but all of the injection plugins I have found so far are for injecting contents of one file into the target file.

Any help would be greatly appreciated.

解决方案

Are you using any kind of modules? ES6 modules, AMD, CommonJS, ...?

If so, you can generate a config module with Gulp where you can inject any variable you want. It would look something like this:

config.tmpl.js

module.exports = <%= config %>

config gulp task

var gulp = require('gulp');
var template = require('gulp-template');
var rename = require('gulp-rename');

gulp.task('config', function() {
  return gulp.src('path/to/config.tmpl.js')
    .pipe(template({config: JSON.stringify({
      timeStamp: new Date()
    })}))
    .pipe(rename('config.js'))
    .pipe(gulp.dest('path/to/config.js'));
});

and finally, in your JS file

var config = require('path/to/config.js');

var object = {
  timeStamp: config.timeStamp
}

这篇关于如何将变量值从GULP注入到JS文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆