How do I get a grunt project's version from co

2019-06-27 09:51发布

I'm looking to integrate my grunt project with TeamCity continuous integration server. I need a way to make the package name that TeamCity generates contain the project's version number, that is found in package.json in the root of the project. I can't seem to find a grunt command that provides this, and am resorting to using grep. Is there an undocumented way of getting a grunt project's version from the command line?

标签: npm gruntjs
1条回答
Bombasti
2楼-- · 2019-06-27 10:44

So in Grunt you can do something like this:

module.exports = function(grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        asciify: {
            project: {
                text: '<%= pkg.name %>',
                options: {
                    font: 'speed',
                    log: true
                }
            }
        }
    });
};

which will pass the name in package.json to any task, in this case, grunt-asciify.

There is also something that does what you ask with regard to getting the version of the project on the command line, simply run npm version in the root of your project, which will return something like this:

grunt-available-tasks (master) $ npm version
{ http_parser: '1.0',
  node: '0.10.21',
  v8: '3.14.5.9',
  ares: '1.9.0-DEV',
  uv: '0.10.18',
  zlib: '1.2.3',
  modules: '11',
  openssl: '1.0.1e',
  npm: '1.3.11',
  'grunt-available-tasks': '0.3.7' }

The last one being the project name and version.

Edit: In regard to your comment, try this:

module.exports = function(grunt) {
    grunt.registerTask('version', 'Log the current version to the console.', function() {
        console.log(grunt.file.readJSON('package.json').version);
    });
}

Edit 2: So I wasn't happy with the Grunt one because of Grunt's verbosity when doing anything. If you want something that will just log the version and nothing else whatsoever, then create a new file called version.js or whatever in your root directory next to package.json. In that file paste this:

module.exports = function() {
    console.log(require('./package.json').version);
}();

And call it with node version.js. I like this approach the best because it's faster than the Grunt one and it's also smaller. So, enjoy!

查看更多
登录 后发表回答