Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

javascript - How to inject variable value into JS file from GULP

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...