perform loading of dynamic JSON data in Grunt

Can a JSON file be loaded from a dynamic source for localisation purposes?

grunt.file.readJSON('src/locales/<%= grunt.task.current.args[0] %>/i18n.json');

A sample section of the Gruntfile is as follows:

module.exports = function(grunt) {

  var i18n = {
    locales: ['en', 'fr', 'de', 'es'],
    default: 'en',
    replacements: function(locale){
      var content = grunt.file.readJSON('src/locales/<%= grunt.task.current.args[0] %>/i18n.json');
      var arr = [];
      for(i in content){
        var replacement = {
          from: i,
          to: content[i].value
        };
      arr.push(replacement);
     }

    return arr;
  }
};
// Project configuration.
grunt.initConfig({
  pkg: grunt.file.readJSON('package.json'),
  replace: {
  build: {
    src: ['local/en/**/*.html'],             
    dest: 'local/<%= grunt.task.current.args[0] %>/',           
    replacements: i18n.replacements('<%= grunt.task.current.args[0] %>')
  }
},

When registering the task:

grunt.registerTask('localise', function(){
  var tasks = [];
  for(i in i18n.locales){
    if(i18n.locales[i] !== i18n.default){

      tasks.push('replace:build:' + i18n.locales[i]);
    }
  }
  grunt.task.run(tasks);
});

Everything works well except for loading the JSON file for replacements.

I've also attempted:

grunt.file.readJSON('src/locales/'+locale+'/i18n.json');

Unfortunately, this did not work either, and I'm unsure of how to proceed.

Could anyone provide assistance?

Thank you

Answer №1

Consider trying this:

'src/locales/' + grunt.task.current.arguments[0] + '/language.json'

Answer №2

Yes, it took some trial and error but I finally got it working:

I made changes to the function that returns the data:

var language = {
  options: ['english', 'french', 'german', 'spanish'],
  defaultOption: 'english',
  updates: function(chosenLanguage){

    var content = grunt.file.readJSON('src/locales/'+ chosenLanguage +'/i18n.json');
    var array = [{from: "/" + chosenLanguage, to: "/english"}, {from: "Test", to: chosenLanguage}];

    for(item in content){
      var update = {
        from: item,
        to: content[item].value
      };

      array.push(update);
    }
    console.log(array);
    return array;
  }
};

Then I initialized an empty array in the default task:

replace: {
  build: {
    src: ['local/english/**/*.html'],             
    dest: 'local/<%= grunt.task.run.args[0] %>/',             
    updates: []
  }
},

This array is updated using its own task

grunt.registerTask('updateConfig', function(chosenLanguage){

    var content = language.updates(chosenLanguage);

    grunt.config('replace.build.updates', content);

});

This task runs just before the replace task:

grunt.registerTask('internationalize', function(){
  var tasks = [];
  for(item in language.options){
    if(language.options[item] !== language.defaultOption){
      tasks.push('updateConfig:' + language.options[item]);
      tasks.push('replace:build:' + language.options[item]);
    }
  }   

  grunt.task.run(tasks);
});

It now gives the correct output. It may not be the most elegant solution, but it gets the job done!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it feasible to unload modules in Node.js once they have been loaded?

app.post('/userlogin',function(req,res){ var Module1=require('./lib/module1'); app.use(Module1); var Module2=require('./lib/module2'); app.use(Module2); }); Is it possible to unload or destroy the modules after they ...

Guide to setting up an express route to utilize passport for secure authentication

I've recently made some adjustments to a boilerplate I created in es6 by downgrading it to an older version, es5. During this process, I had to modify the way I handle exports and requires instead of using imports, but now the routing is working smoot ...

Ways to create a fixed top navigation bar that adjusts content similarly to a non-fixed navbar

I'm looking to achieve a fixed navbar at the top that pushes down content when I open the collapse menu, similar to how it functions in static or regular navbars. Something like this example: (https://getbootstrap.com/examples/navbar-static-top/) but ...

What is the distinction between revealing environment variables in Next.js using the next.config.js as opposed to utilizing the NEXT_PUBLIC prefix?

As stated in the nextjs documentation, to make my environment variables accessible in the browser, I can simply prepend them with NEXT_PUBLIC in my .env.local file, like this: NEXT_PUBLIC_VAR=7 However, it seems that another approach is available where I ...

Unexpected behavior encountered when implementing specific Textfield validation with Material UI

Currently running a project on Node and utilizing React for the front-end, I have encountered an issue with setting .env variables. The project is built with Material UI, and most TextFields are working as expected with their specified validation rules. ...

Why is the `node-config` configuration undefined within a TypeScript Jest environment?

I have a TypeScript module that is functional in both development and production environments. It utilizes https://github.com/lorenwest/node-config. When I attempt to import it into Jest for testing purposes, I encounter an error suggesting that the config ...

Managing rows in the Vuetify grid system

I am currently working on rearranging the layout of rows in specific columns. My goal is illustrated in the attached image - I want the red card item to span across the row it is placed in, but I am unsure how to achieve this. Additionally, I would like th ...

Can someone guide me on how to pass an array as a return value from a function in JavaScript

let warriorsList = []; warriorsList[0] = "Stephen Curry"; warriorsList[1] = "Andre Iguodala"; warriorsList[2] = "Klay Thompson"; warriorsList[3] = "Andrew Bogut"; warriorsList[4] = "David Lee"; function playerStats() { return warriorsList[0]; } console ...

Utilizing Material-UI TextField with targeted onChange event handler

I wrote a function that iterates through an array of objects and creates material-ui TextField elements based on the information provided. The goal is to display an error message if the user inputs characters exceeding the defined maxLength. I want the er ...

Is it possible to use both "npm install --global" and "--save" simultaneously?

I'm curious if it is practical to use both the --global and --save parameters in the npm install command simultaneously. For instance: npm install gulp -g -s From my understanding, since there is no package.json in the npm system folder, I assume th ...

deserializer for Python Django Rest Framework

I am facing an issue with a list structured like this: [{'XPos': {'$': 128.604314661}, 'YPos': {'$': 35.8662354972}, 'clCd': {'$': 1}, 'drTotCnt': {'$': 545}, 'es ...

How can I eliminate text using regular expressions?

Greetings, I am seeking assistance with content removal using regular expressions. Below is the regular expression code I have written: reg = reg.replace(/\|.*?(\|)/g, ''); Input: One-1|two-2|Three-3|Four-4|Five-5 Six-6|Seven-7|Eig ...

Please ensure that busboy on#file completes their task before requesting on#finish

Alright, here's the scenario: req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) { core.upload(filename, file, function(key2) { if (key2 != null) { key = key2; } console.lo ...

Warning in Closure compiler: [JSC_POSSIBLE_INEXISTENT_PROPERTY] The property TextEncoder may not be defined on this object

In my Node.js application, when using the TextEncoder class, I typically do the following: const TextEncoder = require("util").TextEncoder; Although the code functions correctly, I am receiving an undesired warning from the Closure compiler: [JS ...

What is the best way to retrieve data from a JSON object?

Can the status variable be used as a JSON object? What is the method to access the values of action_success and newIndex within the status object? Server: [HttpPost] public ActionResult UploadFiles() { // save file.. return Json(new { action_suc ...

Dealing with API responses after submitting files in Angular

My current setup involves a form where users upload files to my node server. The server then performs some operations and responds with a JSON object. The POST request is not made through the controller, but by submitting the form directly. Once the serve ...

Unable to get jQuery click and hide functions to function properly

Hello, I am currently working on a program where clicking a specific div should hide its own class and display another one. However, the code does not seem to be functioning correctly. Below is my current implementation: $("#one").click(function(){ v ...

What is the best way to align row elements in Bootstrap?

Hey there everyone! I've been grappling with a challenge for the past few days on how to center the contents of a Bootstrap row. Let me elaborate: The row has 12 columns (as is standard in Bootstrap). However, in my design, I'm only utilizing 9 c ...

Ways to resolve the issue: "internal/modules/cjs/loader.js:638 throw err; ^"

I am encountering an error when trying to run my Vue.js project using npm on localhost:8080. Is there a solution to resolve this issue? This error specifically occurs when I attempt to install node_modules and package-lock.json in my Vue folder, which inc ...

One can retrieve a JSON response field value in classic ASP by employing the appropriate coding techniques

Can someone assist me with reading the value of a specific field in a JSON response using classic ASP? For example: I need to extract the deliveryNo and content values from the following JSON response in classic ASP. Can anyone provide guidance on how to ...