Obtain translations from HTML and JavaScript files

Currently, I am working on a project using Angular 1.6 and incorporating angular-translate for internationalization.

The setup for Angular-translate is complete and functioning properly. When I manually include text like:

{{'Test' | translate}}
<span translate>Test</span>

and add the translation key "Test" to both es.json and en.json, Angular translates the keys seamlessly.

Now, my goal is to automate the process of extracting all translated keys from HTML and JS files.

In my research, I came across two packages:

  • gulp-angular-translate-extract
  • gulp-angular-translate-extractor

Within my gulpfile.js, I have a task named "watch" that monitors changes in JS & HTML files. My plan is to incorporate another task called "translation" within the watch task.

I attempted to create this "translation" task using the aforementioned libraries, but none of them successfully extracted translations and added them to en.json & es.json.

Here are snippets of what I tried:

gulp-angular-translate-extract

var angularTranslate = require('gulp-angular-translate-extract');

gulp.task('translate', function () {
    return gulp.src(['./src/app/**/*.html', './src/app/**/*.js'])
        .pipe(angularTranslate({
            lang: ['en', 'es'],
            dest: 'src/app/locale/',
            suffix: '.json',
            prefix: '',
        }))
});

gulp-angular-translate-extractor

var extractTranslate = require('gulp-angular-translate-extractor');

gulp.task('taskName', function () {
  var i18nsrc = ['./src/app/**/*.html', './src/app/**/*.js']; 
  var i18ndest = './src/app/locale'; 
  return gulp.src(i18nsrc)
      .pipe(extractTranslate({
        defaultLang: 'en',         
          lang: ['en', 'es'],
          dest: i18ndest,
          prefix: '',
          suffix: '.json',
          safeMode: false,
          stringifyOptions: true,
      }))
      .pipe(gulp.dest(i18ndest));
});

Despite implementing the above configurations, the extraction task runs when I modify an HTML or JS file, but the translation keys are not being extracted automatically into es.json and en.json.

  • What could be missing in my approach? Do I need additional gulp configurations?

Answer №1

Success! I was able to resolve the issue by utilizing the gulp plugin gulp-angular-translate-extractor

The main obstacle appeared to be related to the use of relative paths:

# Source paths
./src/app/**/*.html
./src/app/**/*.js

# Destination paths
./src/app/locale

I made adjustments to the configuration, specifying different paths which successfully extracted the translations:

var extractTranslate = require('gulp-angular-translate-extractor');

gulp.task('translate', function () {
  var i18nsrc = [path.join(conf.paths.src, '/app/**/*.html'), path.join(conf.paths.src, '/app/**/*.js')];  
  var i18ndest = path.join(conf.paths.src, '/app/locale/')
  return gulp.src(i18nsrc)
      .pipe(extractTranslate({
        defaultLang: 'en',         
          lang: ['en', 'es'],
          dest: i18ndest,
          prefix: '',
          suffix: '.json',
          safeMode: false,
          stringifyOptions: true,
      }))
      .pipe(gulp.dest(i18ndest));
});

The key difference in the code from my original question is the use of these specific paths:

# Source paths
path.join(conf.paths.src, '/app/**/*.html')
path.join(conf.paths.src, '/app/**/*.js')

# Destination paths
path.join(conf.paths.src, './src/app/locale')

The variable conf.paths.src is defined in:

conf.js

exports.paths = {
  src: 'src',
  dist: 'release',
  devDist: 'dev-release',
  tmp: '.tmp',
  e2e: 'e2e'
};

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

The HTML element <a> can have both a href attribute and a onclick attribute

I'm currently facing a challenge with my project - I am trying to create a submenu that includes all sub-pages within a single HTML file. However, whenever I attempt to use both href and onclick, the functionality fails to work as intended. The only ...

What is the correct way to apply styles universally instead of using "*" as a selector?

With Nextron, I was able to successfully run my code, but upon opening the window, I noticed that the body tag had a margin of 8px. Although I managed to change this using the dev tools, I am unsure how to permanently apply this change in my code. When att ...

Converting Erlang Tuple into JSON format

Is there a way to transform a list containing Tuples, Atoms, and Binary strings into JSON format? I stumbled upon an example on Stack Overflow and also came across a resource at https://github.com/rustyio/BERT-JS I am looking for an API that allows me to ...

Tips for verifying a string date using the Ajax Control Toolkit (CalendarExtender) technology

I have a dilemma with two formatted TextBoxes that receive their text value from a CalendarExtender. I need to validate that the first TextBox is greater than the second one, but the values are coming in as strings rather than dates. Ho ...

Issue encountered post installation on host including telemetry.js

I'm encountering an issue while attempting to compile my Gatsby JS website on Netlify. Can anyone provide insight into what might be causing this error? Error: 4:53:02 PM: $ gatsby build 4:53:02 PM: /opt/build/repo/node_modules/gatsby-telemetry/lib/t ...

Utilizing sorting and filtering functionalities on an Angular data table

Recently, I decided to enhance my Angular skills by downloading a demo app. While working on the basics of Angular, I encountered a problem with applying a filter and sort to a data table in the app. Despite referring to some examples, I am uncertain about ...

Having trouble launching the emulator in VS Code for React Native?

I'm having trouble launching the android emulator on VS Code to run React-Native. I already have an emulator set up in Android Studio, but when I try to launch it, I get the error message: Error Failed to launch emulator. Reason: No emulators found as ...

The loading process in CSS can be customized using unique IDs such as loading1 and loading300

My current CSS code looks like this: #loading{ display:none; } The issue I am facing is that I need to hide multiple loading divs, each with an id that includes the word "loading". For example: <div id=loading1></div> <div id=loading42 ...

Issue with bootstrap: the ID is not activating even when it is visible

I am a beginner with bootstrap and I encountered an issue. I created a simple page using bootstrap 5 and included 4 buttons: "Home," "Explore," "Create," and "Share." Here is the code for reference: https://github.com/nguyencuc2586/project2 In the code s ...

JavaScript appendChild method not functioning properly with dynamically created image elements in JavaScript code

I recently encountered an issue while working on a website project. I was trying to create an img element using JavaScript, but ran into a problem when I tried to add the src attribute and then use the appendChild function. I'm unsure if I am missing ...

Iterate over the controls within an UpdatePanel, and interact with JavaScript functions

I'm attempting to change all TextBoxes into labels on my page using the following code: foreach (Control ctrl in masterform.Controls) { if (ctrl.GetType() == typeof(TextBox)) { TextBox t = ctrl as TextBox; t.ReadOnly = true; ...

During the second request, Ajax is unable to retrieve any data

Currently, I am working on a calendar project where I utilize an ajax request upon page load to fetch data from the rails database. Initially, the ajax call successfully retrieves the object during the page load event. However, when I attempt to retrieve ...

Struggling to transmit Fullcalendar configurations via the directive in AngularJS?

I am attempting to use a basic example of the AngularJS Fullcalendar directive from this source: https://github.com/angular-ui/ui-calendar Despite following the instructions, no events are displayed and my custom FullCalendar settings are not applied. I a ...

Determine the precise x and y coordinates of a centered element using JQuery

How can I determine the exact left and top positions of an element? The parent container has text-align: center, causing potential confusion when there are multiple elements on the bottom row. For instance, the first one may have a position of 0px instea ...

Tips for displaying the response next to the corresponding table data (td) cell

When I click the fourth button, the response is showing on the first td. I want to show the response next to the respective td. Below is my code, can someone help me? Thanks. (i.e., here I am getting the $status using a query, but I want this status to di ...

My Laravel API app stores all JSON output inside a data tag. How can I eliminate this tag from the output?

Currently, I am developing an API using Laravel to generate JSON data for an Android application. While my friend is handling the Android part of the project, we are facing an issue where the app cannot retrieve the data from the API. We suspect that the p ...

Guide on making a POST request through axios for REST API:

How can I send a POST request using axios to a REST API? Headers I'm experiencing issues with incorrect headers when making GET requests, and I'm not sure why. Additionally, I've found that the documentation for axios doesn't always w ...

Issue with directive not activating when attribute is changed

I am facing an issue with my website where users can make selections from two dropdowns, and based on those values, attributes are sent to directives for a corresponding function to be called. The problem I'm encountering is that the directives are n ...

"Error message pops up indicating the dispatcher is missing while using npm link with a local project

Currently, I am working on a React component library that I want to integrate into a local project for testing purposes. My initial approach was to use npm link to connect the component library with my local project. However, during this process, I encount ...

Leveraging Javascript/jquery to retrieve image data for a specific frame within a video

Query My aim is to optimize the code for image manipulation on a web browser using JavaScript. One possible solution I am considering is utilizing a video file to reduce HTTP requests. Is there a way to extract a single frame from a video in png, jpg, or ...