javascriptgruntjsgruntfile

<%= %> variable syntax in Gruntfile throws "unable to read"


I'm using the following in my Gruntfile:

grunt.initConfig({
    assets: grunt.option('assets'),
    config: grunt.file.readJSON(path.join('<%= assets %>', 'config.json')) || grunt.file.readJSON('./defaults.json'),
    ...
})

When I execute it, it throws:

>> Error: Unable to read "<%= assets %>/config.json" file (Error code: ENOENT).
    >> at Object.util.error (/.../prj/node_modules/grunt-legacy-util/index.js:54:39)
    >> at Object.file.read (/.../prj/node_modules/grunt/lib/grunt/file.js:247:22)
    >> at Object.file.readJSON (/.../prj/node_modules/grunt/lib/grunt/file.js:253:18)
    >> at Object.module.exports (/.../prj/Gruntfile.js:10:28)
    >> at loadTask (/.../prj/node_modules/grunt/lib/grunt/task.js:325:10)
    >> at Task.task.init (/.../prj/node_modules/grunt/lib/grunt/task.js:437:5)
    >> at Object.grunt.tasks (/.../prj/node_modules/grunt/lib/grunt.js:120:8)
    >> at Object.module.exports [as cli] (/.../prj/node_modules/grunt/lib/grunt/cli.js:38:9)
    >> at Object.<anonymous> (/usr/local/lib/node_modules/grunt-cli/bin/grunt:45:20)
    >> at Module._compile (module.js:425:26)

Wondering if this is because the assets var isn't defined at the point I'm trying to use it? Or is the <%= %> syntax not allowed to be used in this fashion?

According to this answer, it looks like it should work -- which I found because previously I was just using var assets = grunt.option('assets'), but that was throwing SyntaxError: Unexpected token var for some reason. (Before I messed with it, it looked like this:)

module.exports = function(grunt) {
    require('load-grunt-tasks')(grunt)

    var util = require('util'),
        path = require('path'),
        pkg = require('./package.json')

    var assets = grunt.option('assets'),
    var config = grunt.file.readJSON(path.join(assets, 'config.json')) || grunt.file.readJSON('./defaults.json')

    grunt.initConfig({
        ...
    })

What's the proper, grunt way of using a module or declaring a variable inside a gruntfile like this? And/or, can I fix the problem with Unexpected token var?

(Note: It's not the config file that I'm having trouble loading, it's the fact that the assets path from grunt.option() appears to not be interpreted)


Solution

  • Seems like you want to read a custom json file. Remember that even grunt script is just JavaScript and node requires work just fine. So you can do something like

     var conf = grunt.file.exists(assets + '/ '+ 'config.json') ? require(assets + '/ '+ 'config.json') : {};
    

    You can then use your config variable around where ever.

    conf.foo || 'default'
    conf.bar
    

    In either case you need to declare assets variable before usage. In require or in initConfig

    Update

    Also,
    You have a extra comma after var assets = grunt.option('assets'), Either remove that or remove the var in next line