Issue - The module ./en.json could not be located when using the vue-i18n plugin

I recently integrated the i18n plugin into my existing Vue project to add localization. After following all the installation instructions from various sources (such as here), I made sure that each locale has its own file under /src/locales with the correct naming convention (/src/locales/en.json).

The code snippet from my /src/i18n.js file looks like this:

import Vue from 'vue';
import VueI18n from 'vue-i18n';

Vue.use(VueI18n);

function loadLocaleMessages() {
  const locales = require.context('./locales', true, /[A-Za-z0-9-_,\s]+\.json$/i);
  const messages = {};
  locales.keys().forEach((key) => {
    const matched = key.match(/([A-Za-z0-9-_]+)\./i);
    if (matched && matched.length > 1) {
      const locale = matched[1];
      messages[locale] = locales(key);
    }
  });
  return messages;
}

export default new VueI18n({
  locale: process.env.VUE_APP_I18N_LOCALE || 'en',
  fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
  messages: loadLocaleMessages(),
});

However, when running the code, an error occurs within the loadLocaleMessages() function while trying to load the /src/locales/.json files. Specifically, the error is thrown at this line:

messages[locale] = locales(key);

An error message pops up saying:

Cannot find module './en.json'

With key set to ./en.json and locale being en, it seems like everything should be working correctly. Can anyone pinpoint what might be causing this particular error?

Answer №1

It's quite embarrassing, but I finally figured out that the root cause of the issue was a simple trailing comma in my en.json file.

{
  "message": "hello i18n !!",
}

I mistakenly had a comma at the end instead of it being

{
  "message": "hello i18n !!"
}

This oversight may have been due to my habit of using eslint which requires trailing commas in my JS code.

Lesson learned: Always pay attention to compilation errors in your IDE...

Answer №2

After encountering the same issue, I discovered that it was due to not adding any content to the Json file I created.

Be aware of this in case you come across it as well.

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

Unlocking the power of bitwise operations in VueJS with Javascript

Forgive me if this sounds like a silly question. I'm currently using vue-moment within my Vue.js application and I have the following code snippet: <!-- date = '2020-03-23 01:01:01' --> <span>{{ date | moment('from', & ...

Retrieving information from an Express.js API using React.js. Postman requests are successfully communicating with the API

Hey there, I'm facing a little issue and could use some help. I have an Express application that is working perfectly with requests from Postman (adding, deleting, etc.). Now, I want to connect my client side (React.js) with the existing API using the ...

Troubleshooting Issue with Node.js and Postman: Error encountered while attempting to

Consider the following code snippet: const fs = require('fs'); const express = require('express'); const app = express(); const bodyParser = require('body-parser') // using middleware app.use(express.json()); app.use(bodyPar ...

Display the username on a Meteor React component

I'm facing an issue with one of my React components, which serves as the main layout for my application. It includes a navigation bar that displays the username of the currently logged-in user. The problem arises when Meteor.user() returns undefined d ...

What is the best way to make an element fixed vertically in a mobile browser while also enabling horizontal scrolling?

When using a Desktop browser, I have found a javascript code that allows me to vertically fix an element while still enabling horizontal scrolling. The element is repositioned with each scroll event. You can test this out by trying both horizontal and vert ...

"Encountering a 405 error when transmitting information from an HTML file to a Python Flask server using 'GET / HTTP/1.1'

As someone who is brand new to the world of python and AJAX, I have been piecing everything together from various sources online including examples and Flask documentation. So far, I have managed to make some progress. My goal is to send latitude and longi ...

Cannot retrieve JSON values in Filestack v3

I am currently working with Filestack (Filepicker) V3 to upload multiple files and retrieve filename, url, and mimetype. Based on the Filestack documentation for this latest release and a previous question that was asked here, I have implemented the follow ...

Determine if a user's inputted number matches a randomly generated number using Javascript

I am trying to generate a random number, prompt the user to input a number, compare the two, and display a popup indicating whether they match or not. Below is the code that I have written for this functionality. function generateRandomNumber() { ...

When Controller Scope Goes Missing in ng-repeat

Upon glancing at my code, it should be evident that I am a newcomer to the world of Angular. I am currently developing an application that enables users to search for text, queries a database whenever the value in the text input changes, and displays a li ...

What exactly is the data type of setInterval in TypeScript?

If I want to define the type of a variable that will be used with setInterval in the following code snippet: this.autoSaveInterval = setInterval(function(){ if(this.car.id){ this.save(); } else{ this.create(); } ...

Access a portion of a file located on a distant server

Is it possible to read part of a remote file using Ajax without relying on server-side technologies like PHP? I believe the HTTP Range header could be utilized for this purpose, but how can we set it with Ajax? Can we even set HTTP headers in Ajax request ...

Selecting an object from JSON data with Angular using $routeParams

I am attempting to showcase information from a JSON file that is structured like this: [ { "category":"category1", "link":"category1", "expand":false, "keyword":"category1, category1 online, category1 something" }, { "category":" ...

Utilize the parsing functionality in three.js to extract JSON geometry data

After exporting a model from Blender using the three.js exporter and successfully loading it with the JSONLoader, my next challenge is to store the JSON information in a variable and parse it to display the model without having to load an external file. T ...

Ensure that the number is valid using Express Validator in Node.js

One thing that I've noticed when using express validator is the difference between these two code snippets: check('isActive', 'isActive should be either 0 or 1').optional({ checkFalsy : false, nullable : false }).isInt().isIn([0, 1 ...

Showing particular PHP array retrieved from MySQL

Currently, all columns from the MySQL result are being converted to JSON and displayed on the screen. However, I am interested in only printing two specific columns - $row['name'] and $row['gender']. Any suggestions on how to achieve th ...

A step-by-step guide to activating multi-selection in the Primary SideBar of Visual Studio Code using your custom extension

Currently, I'm in the process of developing an extension for Visual Studio Code where I've added a new activityBar containing treeViews that showcase information pulled from a JSON file. My goal is to enable users to multi-select certain displaye ...

The HSET command in the Redis client for Node.js is not working

I have been developing a DAO (data access object) for the project I am currently working on, which acts as an abstraction of a redis database. Below is the code relevant to my upcoming query: var redis = require("redis"); var _ = require("underscore"); va ...

The error message states that the argument type 'AsyncSnapshot<Object?>' is not compatible with the parameter type 'Map<String, dynamic>'

In my code, I had a factory method for converting json data into an object. This method accepted Map<String, dynamic> as an argument from the sqlite database like this: factory Lecturer.fromJson(Map<String, dynamic> json)=>Lecturer( nam ...

Adjusting the waterlevel model attribute to its standard value

In my Sails.js project, I am looking to reset a model attribute back to its original default value. By default value, I mean the value specified using defaultsTo in the model file. I have attempted methods such as: model.update({id:exampleId}, {myAttrib ...

In Next.js, a peculiar issue arises when getServerSideProps receives a query stringified object that appears as "[Object object]"

Summary: query: { token: '[object Object]' }, params: { token: '[object Object]' } The folder structure of my pages is as follows: +---catalog | | index.tsx | | products.tsx | | | \---[slug] | index.tsx | ...