Importing JSON files dynamically in Typescript with Quasar/Vue using different variable names

Currently, I am in the process of developing an application utilizing the Quasar framework with Typescript. Managing a large number of JSON files for dynamic import has proven to be quite challenging due to the impracticality of manually importing hundreds of files.

In order to load the JSON data in my Vue component, I have a scripts file set up. However, I encountered an issue when trying to dynamically import a file using a variable filename, possibly because the webpack is not including that specific file.

When manually typing out the filename as a dynamic import, it works smoothly:

import('src/assets/myData.json').then(myData => console.log(myData))

On the other hand, trying to build the filename using a variable string does not work:

const fileName = 'myData';
import(`src/assets/${fileName}.json`).then((myData) => console.log(myData));

This approach triggers an error message in the browser console:

Uncaught (in promise) TypeError: Failed to resolve module specifier 'src/assets/myData.json'

It seems like the webpack does not include the myData.json file due to the string interpolation technique used. The second example does not display the file in the dev tools browser, whereas it appears in the first example. Is there a way to incorporate these data files without manual input? Given the abundance of such files, manual insertion is not a feasible solution. Any insights or suggestions would be greatly appreciated. Thank you!

Answer №1

The solution that worked for me was by incorporating a relative path in the dynamic import statement, as shown below:

const fileName= 'myData';
import(`../resources/${fileName}.json`).then((myData) => console.log(myData));

Although I'm not entirely certain of the reason behind why this resolved the issue, it appears that this approach ensured proper inclusion by webpack. Sharing this here in case it proves beneficial to others.

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

What is the best way to integrate Vuex State data into methods?

Reviewing the code snippet below: <template> <div :id="svgId" class="svg-container"></div> </template> <script> import { mapState } from 'vuex' export default { name: 'Space', data: function() { ...

Rearrange the items within a category

Currently, I am engaged in JSON parsing and the outcomes of my efforts are as follows; { "alias": { "OUTLET_NAME": "OUTLET_NAME" }, "displayFieldName": "OUTLET_NAME", "feature": { "features": [ { "attribute": { ...

What is the best way to add a href attribute to a carousel item using Vuetify 2?

Currently, I am working on a project using Vuetify 2 and have encountered an issue with redirecting users to different websites when they click on images within a carousel. Each item in the carousel should link to a unique website, requiring multiple href ...

What is the best way to define the typings path for tsify?

My TypeScript sources are located in the directory: src/game/ts The configuration file tsconfig.json can be found at: src/game/ts/tsconfig.json Additionally, the typings are stored in: src/game/ts/typings When running tsc with the command: tsc --p s ...

Move information from one page to another

I'm currently using Ionic 2 and attempting to pass data from one page to another. Specifically, I want to transfer the data of a selected list item from the first page (quickSearch) to the second page (quickSearchDetail). To illustrate this, refer to ...

Issue with Angular 7: "Unspecified name attribute causing control not found"

As I delve into the creation of my initial Angular application, I find myself faced with a series of errors appearing in the development mode console: ERROR Error: "Cannot find control with unspecified name attribute" ERROR Error: "Cannot f ...

RxJS and asynchronous operations - Mastering the flow of execution

Exploring the concepts of async with RxJS is my current goal; I created this example to dive into how async function calls interact within RxJS observables. The outcome looks like this: func1 --- 10 func1 --- 20 func1 --- 40 func1 --- 30 switch ...

Ways to serialize responses wrapped by JAXBElement into JSON without the JAXBElement wrapper?

My http service is built using Spring (v4.0.5) with endpoints configured using Spring Web MVC. The responses are JAXB2-anotated classes generated from a schema and wrapped in JAXBElement due to the lack of @XmlRootElement annotations in the generated class ...

Using Axios: Manually Adding the X-XSRF-TOKEN Header

Currently, I am in the process of building a server-side rendered application with Vue. The API backend is created using Laravel framework and for sending requests to the API, I am utilizing axios. My current challenge involves making a POST request on th ...

Issues arise when attempting to include the src attribute within the template tag in a Vuejs and Laravel project

After starting a project with Vuejs and Laravel using Laravel Mix, I encountered an issue. When attempting to split my component into separate files and load them in the .vue file as follows: <template src="./comp.html"></template> &l ...

Error: Export keyword unexpectedly found in TypeScript project

Having a problem while running Jest in my TypeScript project. The TypeScript file is located at rootDir/src/_services/index.ts and Jest is throwing an error: ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,je ...

Display the content of an associative array in PHP by converting it into JSON format

I am currently learning PHP and working on a PHP script to extract data from my online database hosted on my altervista personal webpage, and converting it into JSON format. Everything is working fine when I use the "echo" command to display elements from ...

Add JSON data to an array of movie clips using ActionScript 3.0

I'm currently developing an air app in flash cs6 using as3. I have a requirement to send a JSON to a movieclip and integrate a "timeline" feature into my application. Below is the code snippet I am working with: function onCompleteLoadTimeline(event: ...

Experiencing difficulty fetching JSON data from a remote URL due to an error

I'm attempting to load a remote JSON file from this link. Initially, I used the $http.get function, but encountered the following error message: CORS 'Access-Control-Allow-Origin' Switching to JSONP didn't solve the issue either. ...

I am struggling with utilizing the data that has been fetched in JavaScript. Despite successfully retrieving the data, I am facing difficulties in effectively using it in

I am facing an issue where I am unable to utilize the data after fetching it from a local JSON file. Below are the screenshots showcasing the problem: Here is the data displayed in the console: Here is the code snippet: fetch('api_link.json') ...

Experience inadequate test coverage while conducting unit tests in Vue.js

I'm currently working on Vuejs unit testing using karma+mocha+chai+webpack and aiming to achieve code coverage with istanbul. However, I've encountered an issue where importing certain utility functions or components into the component being tes ...

ES6/JS: Locate a specific text within a nested object and return a true value

I need help filtering a vuetify data-table. You can find the codepen link here: https://codepen.io/rasenkantenstein/pen/MWYEvzK. I have a filter with the string "Ice", and I want to retrieve all records that contain an ingredient with "ice" in its name. [ ...

Navigating through nested object properties

I'm encountering an issue while trying to access a nested object property. <th data-toggle="tooltip" data-placement="bottom" v-for="schedule in employee.daily_schedules">{{schedule.start}}-{{schedule.end}}-{{schedu ...

Is there a way to create a Swift object from a JSON object that is easy to read

Upon receiving data from the server, it appears in JSON format with the following structure: [{ "_id": someRandomID; comment = { identifier = someRandomIdentifier; text = someRandomText; }; }] The data is obtained using socket ...

Eliminating an array from the reverse computed method in Vue.js

Hello, I'm trying to figure out how to eliminate an array from a reversed method. Can someone assist me with this? Below is my code snippet: const app = Vue.createApp({ data() { return { app_title: 'Simple Checklist App&a ...