I am just getting my head around npm and creating build with npm/webpack/build. How can I add a timestamp as part of the filename to a bundle.js that is generated with npm/webpack? Is there a module available?
There's no existing module that I'm aware of. However, this can be achieved using the following solution:
bundle.js
, i.e. rename the file to something like: bundle-2018-02-14-10-16-22.js
.post
hook to invoke the custom nodejs script.Note: I'm assuming that you execute the npm run build
command to produce bundle.js
. In which case the solution below utilizes an npm-script named "postbuild"
to invoke the nodejs script which appends the timestamp.
timestamp.js
Create a custom nodejs script as follows. Let's name the file timestamp.js
.
const fs = require('fs');
const path = require('path');
const src = process.argv[2];
if (!src) {
throw new Error('Missing file path argument');
}
const tstamp = new Date().toISOString()
.replace(/\.[\w\W]+?$/, '') // Delete from dot to end.
.replace(/\:|\s|T/g, '-'); // Replace colons, spaces, and T with hyphen.
const ext = path.extname(src);
const fname = path.basename(src).replace(ext, '');
const fpath = path.dirname(src);
const dest = path.join(fpath, `${fname}-${tstamp}${ext}`);
fs.rename(src, dest, function (err) {
if (err) throw err;
});
package.json
In the scripts
section of your package.json
add a postbuild
script to invoke timestamp.js
as follows:
{
...
"scripts": {
"build": ... ,
"postbuild": "node timestamp path/to/bundle.js"
},
...
}
Note: your current build
script should remain as-is.
Running
When executing the npm run build
command your build steps will run as normal. Upon completion the postbuild
script will automatically be invoked, appending the timetsamp to the file name as necessary.
Notes
The path/to/bundle.js
part in the postbuild
script should be changed to the actual path where your resultant bundle.js
file is created.
The example postbuild
script above currently assumes timestamp.js
resides in the same directory as package.json
. You could, (for example), save it in a hidden directory named .scripts
which resides in the same directory as package.json
. In which case your postbuild
script would need to be changed to:
{
...
"scripts": {
"build": ... ,
"postbuild": "node .scripts/timestamp path/to/bundle.js"
},
...
}
The timestamp appended to the file name currently uses the format: YYYY-MM-DD-hh-mm-ss
.
You'll notice that ES6 Template Literals are utilized in timestamp.js
at the line reading:
const dest = path.join(fpath, `${fname}-${tstamp}${ext}`);
However, if the version of node your running doesn't support these, then replace that line with the following (i.e. use the +
operator for string concatenation instead):
const dest = path.join(fpath, fname + '-' + tstamp + ext);