Large modern libraries include version and additional information as a property. Lodash for example
puts its semantic information in the banner and attaches it to the exported _
object.
1 | /** |
AngularJs has meta information object attached as angular.version
angular.version
Object {full: "1.4.0", major: 1, minor: 4, dot: 0, codeName: "jaracimrman-existence"}
If you produce a library to be used by others, make sure to attach the version and other meta information. Having version information at runtime is great help during debugging.
I assume that your library has an NPM package.json
with at least the version string. It would be
great if you followed semantic versioning.
To create a nice banner I prefer using grunt-contrib-concat plugin. It concatenates source files and can add the banner to the output file. For example freeze-prototypes project has the following Gruntfile.js
1 | var pkg = grunt.file.readJSON('package.json'); |
Running grunt concat
command produces dist/freeze-prototypes.js
with a nice banner, useful to anyone
trying to understand what are the libraries running at runtime, especially if using single letter objects.
1 | /** |
Version string property
Let us also add version (and author, description meta) information to the exported library itself,
so we can fetch it at run time from the browser console. To achieve this I attach property version
to the exported library. The version
property is an object with placeholders that can be replaced
during the build step. For example see functional-pipeline
project.
By default, the exported function fp
has an object with placeholders.
1 | function fp() { ... } |
During the concat step, we can transform the source and put the actual values read from
the package.json
file into the placeholders.
1 | // pkg is the loaded package.json file |
The output file will have something like this
1 | ... |
Using grunt templates
To avoid custom tags and replacement, we can use grunt's built-in Lodash template
api. We can use <%= %>
to put a value
inside the source file.
1 | function fp() { ... } |
We can also attach the loaded package.json
to the Gruntfile config object to be able to
refer to the properties inside the template via pkg
property.
1 | var pkg = grunt.file.readJSON('package.json'); |
The function insertMeta
is unnecessary - it just passes the source to the grunt.template.process
method;
we can use point-free style call.
1 | concat: { |
See the complete Gruntfile.js for details.
- You can also embed Git commit id in addition to the version string, see Deployed commit blog post.
- If you want version information inside Angular modules, see Angular module info.