Reputation: 3776
I am doing bundling and minification for javascript files. I am doing this using gulp. Now I want that if I make any change in any of my file and hit gulp then it generate a new bundled and minified file with version number like:
<script src="https://cdn.test.com/bundle-1.0.0-min.js/"></script>
then
<script src="https://cdn.test.com/bundle-1.0.1-min.js/"></script>
I want to do this using gulp because I am already using gulp for other purposes. And one more thing if this is possible then is there any way that I don't specify version no in my html page every time I make a change and my html page get the latest version by its own somehow.
Upvotes: 1
Views: 1579
Reputation: 12452
This is just a rename of the file in general. But this should really not be an automated task to increment the version number. Otherwise you will be quickly getting a version like 1.0.2092
what is not helpful. I would suggest to read the version out of the package.json
and use it for the name of the file. Should be pretty easy, if you already worked with gulp
.
If you don't want to use the global version (version
entry) of your package.json
, you could add an own entry for your bundle version. Or even use a different file than package.json
. You could even use that as config for which files should be bundled, to have everything in one place:
{
"bundle": {
"version": "1.0.1",
"files": [
"path/to/file-one.js",
"another/file.js",
"..."
]
}
}
Just a quick example:
var pkg = require("./package.json");
var gulp = require("gulp");
var rename = require("gulp-rename");
gulp.src(pkg.bundle.files)
.concat("bundle.js")
.pipe(uglify())
.pipe(rename(function(path) {
path.extname = "-" . pkg.bundle.version + "-min" + path.extname;
}))
.pipe(gulp.dest("./"));
Note: instead of rename
you can just set the concat
name, but I like to split this. But just to be complete:
.concat("bundle-" + pkg.bundle.version + "-min.js")
About the second parts of your question, to replace things in your files:
This would be possible if you build your html pages too, and replace/inject the relevant path into it. You could use the version of the package.json
again, to build it and replace. Or use tools like gulp-inject
. That simple tool can add js
and css
files into your html templates. Just create an area where they should be placed in the html file, like: <!-- inject:js --><!-- endinject -->
. Afterwards it is a simple gulp
taks too:
var pkg = require("./package.json");
var gulp = require("gulp");
var inject = require("gulp-inject");
gulp.src("dev/index.html")
.pipe(inject("bundle-" + pkg.bundle.version + "-min.js"))
.pipe(gulp.dest("prod/"));
Upvotes: 1