bsr
bsr

Reputation: 58662

Refer to static json data from javascript and grunt

I have some const values, which are used throughout the application as well as by jade for static code generation.

I was defining the data in file (const.js) as below.

my.const = (function () {
    return {};
}());

my.const.testType = Object.freeze({
    main: {key: 1, value: "Main"}
});

I include this file with script tag, and the variables are accessible to my application.

But, I do not find a way to read this file, and access the data object, my.const in jade. For that, I have to create a json file and configure grunt as

jade: {
            dist: {
                options: {
                    pretty: true,
                    data: function(dest, src) {
                        console.log(dest, src);
                        return grunt.file.readJSON('app/const.json');
                    }
                },
                files: [...

I use grunt-contrib-jade plugin.

I cannot use const.js as it needs to be a valid json file (api). So, I have to keep and maintain 2 files (js and json) with same data. How can I either

  1. read the js file (const.js) with grunt and access the data (my.const) OR
  2. include the data from json file, statically so that scripts below can acccess the data. Simply including json file gives error (Uncaught SyntaxError: Unexpected token :)

or is there a better way (any grunt plugin to generate the js file, ...). I cannot think any.

Thanks.

Upvotes: 0

Views: 621

Answers (1)

udidu
udidu

Reputation: 8588

Assuming you are using node js, in your const.js file, add at the bottom:

.
.
if(module && module.exports) {
    module.exports = m;
}

At the top of your grunt file, require the const.js file:

var m = require('../path/to/const.js');

And then, in your grunt configuration data function:

                data: function(dest, src) {
                    console.log(dest, src);
                    return m;
                }

Upvotes: 1

Related Questions