Svelte language switcher experiencing technical difficulties

Currently delving into Svelte 3, I embarked on a project intended to be shared on GitHub in English. However, I realized that some of my friends do not speak English. To accommodate different language preferences, I decided to create a language switcher. Here's what I came up with:

<script lang="typescript">
  var selectedLang = "en_us";
  const _lang_filename = "./lang/%.json".replace("%", selectedLang);
  import lang from _lang_filename;
</script>

<div id="_app_">
  <h1>{lang.welcome}</h1>

  <button
    on:click={() => {
      selectedLang = "pt_br";
    }}>Português (Brasil)</button
  >
  <button
    on:click={() => {
      selectedLang = "en_us";
    }}>English (United States)</button
  >
</div>

Encountering an issue with the import of the lang file, I encountered an Unexpected Token error when trying to use a variable. I attempted incorporating string.replace() within the import itself, but to no avail.

Answer №1

One common misunderstanding is how Svelte operates.

In contrast to other frameworks, the section between <script> and </script> is only executed once. This means that even if you click the button multiple times, the value of lang_filename will never change. To indicate to the compiler that one variable depends on another, you need to make it reactive by using $:.

let selectedLang = "en_us";
$: _lang_filename = "./lang/%.json".replace("%", selectedLang);

So now, _lang_filename will be updated whenever selectedLang changes.

(Note: Consider using template literals instead)

$: _lang_filename = `./lang/${selectedLang}.json`

After obtaining the correct filename, the next step is to load the actual file. While you can perform a dynamic import, the HTML specifications limit importing only javascript files this way.

However, you can use fetch to retrieve the file. Create a variable lang to store your language object, and a loader function to load it.

let lang = {}
function load(filename) {
  lang = await fetch(filename).then(res => res.json())
}

To ensure that Svelte reruns load whenever the filename changes, utilize reactivity:

$: load(filename)

You could pass in selectedLang here and construct the path in the load function as well.

For completeness, here is the complete script:

<script>
    let selectedLang = "en_us";
    let lang = {}

    $: loadLanguage(selectedLang)

    async function loadLanguage() {
        lang = await fetch(`./lang/${selectedLang}.json`).then(res => res.json())
    }
</script>

Keep in mind that initially, lang will be an empty object, resulting in a brief display of undefined before loading.

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

Exploring time differences in Javascript

I am trying to save a JSON AJAX response from the server in the browser's localStorage for a duration of one minute, along with a timestamp generated using new Date().getMinutes(). Upon triggering $(document).ready, I aim to check the stored timestam ...

The dynamic Vue.js transitions and effects are like a magic

I am using a v-for to render multiple child components: <div v-for="(pass) in scoringPass" :key="pass.decision"> <Pass :pass="pass"/> </div> Each of these child components contains a transition tag: &l ...

Mastering the correct way to handle the "window" object within the Node.js testing environment using JSDom

Testing my React app using Tape and JSDom involves importing a specific module at the beginning of each test JS file: import jsdom from 'jsdom' function setupDom() { if (typeof document === 'undefined') { global.document = jsdom ...

steps for repairing a scoreboard

Is there a way to make my scoreboard increase by +1 point instead of +10? In my JavaScript code, I used intervals as it was the only solution that worked: let scoreInterval = setInterval(updateScore); let score = 0; function updateScore() { var poin ...

Require that JSX elements begin on a new line if the JSX element spans multiple lines

Which eslint rule favors the first syntax over the second when JSX code spans multiple lines? Currently, Prettier is changing `preferred` to `notPreferred`. const preferred = ( <tag prop={hi} another={test} \> ); const ...

The jQuery slider's next button is not functioning as intended

jQuery('#slider-container').bjqs({ 'animation' : 'slide', 'width' : 1060, 'height' : 500, 'showControls' : false, 'centerMarkers' : false, animationDuration: 500, rotationS ...

Ajax updates previous text to new text upon successfully completing the task

I have a question regarding changing text using AJAX after success. I have written this AJAX code which is functioning properly. However, I aim to replace the old text with new text in the .chnged div. For instance: <input type="text" name="text" va ...

Using VueJS to Bind an Array of Integer Values to Checkbox Models

I encountered a discrepancy between VueJS 1.0 and VueJS 2.0 regarding checkbox behavior. In VueJS 1.0, when binding checkboxes to a list of integers in v-model, the integers do not register as checked attributes. Below is the HTML code snippet: <div i ...

Applying the document height to window height ratio to create a scale ranging from 1 to 100

My goal is to create a scroll bar using two divs with heights of 110px and 10px. The smaller one will be nested inside the taller one, allowing for adjustment of its margin-height from 0 to 100px while still fitting within the larger div. When I refer to ...

Is the file corrupt using node.js?

Looking for ways to determine if a file is corrupted using node.js? I have attempted various File System methods, such as fs.readFile, fs.open, and fs.access, but all of them are showing an OK status. However, I am confident that my file is corrupted base ...

Build a custom form for the purpose of exporting an HTML file

I am in search of a way to provide my users with various "feature" choices that will assist them in creating an HTML file for an email. I already have the code ready for each feature, but I want users to be able to select a feature (such as Hero Image Head ...

Transforming a vertical table into a horizontal layout

I'm facing an issue with transforming the database object for table display. My database contains a table structured like this. name total date Awoc1 100 9/14/2022 Awoc1 200 9/15/2022 Awoc1 300 9/16/2022 Awoc2 100 9/14/2022 Awoc2 ...

Rotating camera independently from its parent in Three.js

I have a scenario where an Entity is traversing a CatmullRomCurve3 path, moving left with the left or down arrow keys and right with the right or up arrow keys. Initially, I encountered an issue where I wanted the Entity to face perpendicular to the path ...

Utilize the class or interface method's data type

In the context of a child component calling a callback provided by its parent, this situation is commonly seen in AngularJS. As I am utilizing TypeScript, I aim to implement strong typing for the callback in the child component. Here is the initial stat ...

Adaptively linking to the property of a deeply nested object

Attempting to bind to a property of a nested object using [(ngModel)], but facing the challenge that the path to the property is dynamically set. Consider the following three classes: class A { p1: C constructor() { p1 = new C("A") } } class B { p2: ...

What is the best way to fetch the class name of an element in JSDOM?

In my current project, I am facing a challenge with extracting the className of an element using JSDOM. Despite being able to locate the element successfully, I have been unable to find any relevant examples or documentation on how to retrieve the classN ...

Strategies for displaying error messages in case of zero search results

I am currently developing a note-taking application and facing an issue with displaying error messages. The error message is being shown even when there are no search results, which is not the intended behavior. Can someone help me identify what I am doing ...

Experience the convenience of uploading photos using jQuery Dialog on your ASP.NET MVC website

I am in the process of developing an ASP.NET MVC 3 application and encountering an issue with using a jQuery Dialog to upload a photo. Despite my code implementation, the HttpPostedFileBase object within my model (representing the file to be uploaded) cons ...

Utilizing an array as a child component in conditional rendering with vue.js

I have a Laravel API and the front end is built with Vue.js + Laravel. I am fetching data from the API and passing it to the view. Now, I want to implement conditional rendering based on certain criteria. Here's what my array looks like: "data" =&g ...

Customizing Marker Images in Google Maps JavaScript API

Currently, I am using a workaround to rotate a custom image marker in Google Maps. The issue I am encountering is regarding sizing. For example, if my PNG image is 400px wide and 200px high. When rotating the image so the width becomes vertical, it gets ...