Gruntfile.js task can't read package values?
Asked Answered
V

1

6

In Gruntfile.js' initConfig function, I have the following:

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
      '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
      '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;',
    concat: {
      options: {
        banner: '<%= banner %>',
        stripBanners: true
      },
      dist: {
        src: ['src/<%= pkg.name %>.js'],
        dest: 'dist/<%= pkg.name %>.js'
      }
    },

I'm creating the pkg variable and then attempting to pull the name from the object under concat.dist, because this is coming from a new grunt-init template. I'm getting Cannot read property 'name' of undefined when running concat:dist. I've verified the existence of the file and the node "name" in the package.json" file.

Given I'm new to node, I'm not sure if these closures persist when calling grunt tasks and if they do, am I using the wrong convention? Is this even possible?

Vizcacha answered 30/12, 2014 at 15:43 Comment(2)
Is there a "name" in your package.json file?Trevino
yes, sorry, forgot to clarify that. The concern is the "of undefined" which usually means a null pointer error and thus an empty object. I'll clarify, thanksVizcacha
T
6

My guess is that it can't read your package.json file for some reason. Either because it doesn't exist (named differently perhaps?) or doesn't have read permissions. You can create a simple test to see if you can access the file from Grunt:

grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    logvar: {
        data: '<%= pkg.name %>'
    }
});

grunt.registerTask('logvar', function() {
    grunt.log.writeln(grunt.config.get('logvar').data);
});

Now just run grunt logvar from the command line. If you still get the error, well then we've eliminated anything else, and that means your package.json file is inaccessible. I would recommend checking that it is in the same directory as Gruntfile.js and that it has read permissions.

Trevino answered 30/12, 2014 at 15:59 Comment(3)
logvar worked!!! Now I'm totally confused. Thanks for the suggestion though, very useful and gave me a lot of new insightVizcacha
If that worked, then I would get your setup down the minimal possible and see where things are breaking... are you sure it's the concat task? Maybe something "above" it is breaking things? Maybe create another var (like banner) and use that to see if it works?Trevino
It must be before that... I've hard coded the name and I'm getting the same problem. Thanks!Vizcacha

© 2022 - 2024 — McMap. All rights reserved.