How to add a variable value to a JS file from GULP

Hope this is a quick question.

What I'm trying to do is add a timestamp to a Javascript object in a JS file, while the file is created using GULP. Basically, in the file.js file, I have an object where I would like to have an object.timeStamp object equal to the GULP build time.

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

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

Any help would be greatly appreciated.

+5
source share
2 answers

Do you use any modules? ES6, AMD, CommonJS, ... modules?

If so, you can create a config module with Gulp, where you can insert any variable you want. It will look something like this:

config.tmpl.js

module.exports = <%= config %> 

Gulp configuration 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 } 
+8
source

OK, so I realized that it helps me where I want to be. The first is using 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 the property in the object, which is a function, and sets the timeStamp property that I was looking for, getting the value from the timeStamp variable introduced above using gulp -header, for example:

In the JS file, the header function inserts the following:

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

And then my function in the JS object is simple:

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

Which, when called, starts and sets a timestamp inside the object.

There seems to be an easier way to do this, but for now it works.

If you have ideas for improving it, I would like to hear them!

+1
source

Source: https://habr.com/ru/post/1237683/


All Articles