How to inject variable value into JS file from GULP

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-30 19:06:59

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
}

O.K., so I figured out a workaround that gets me where I want to be. The first this is using the gulp-header to insert a variable declaration into my Javascript file using this code:

In GULP:

    var d = new Date();
    .pipe(header("var timeStamp = '" + d +"';"))

Then, in my Javascript file, I set up a property in the object that is a function, and sets the timeStamp property I was looking for by getting the value from the timeStamp variable injected above using the gulp-header, like this:

In the JS File, the header functionality inserts this:

    var timeStamp = 'Tue Dec 08 2015 15:15:11 GMT-0800 (PST)';

And then my function, in the JS Object is simply this:

   ts: function(){
    object.timeStamp = timeStamp;
   },

Which, when called, runs and sets the timestamp inside of the object.

It seems like there should be an easier way to do this, but for now, this is working.

If you have any ideas on making it better, I would love to hear them!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!