What is the best way to implement a require function for an external JSON file in the final build of a Vue.js web application?

I have developed a quiz web application that is currently only accessible locally on my machine. The logic and architecture of the app are all set up, but I am facing a challenge: how can I have the question list pulled from "questionOptions.js" externally on the production version? This way, I can easily update or modify the questions without having to export a new build version each time.

Currently, in development mode, the question list is sourced locally, and I am unsure how to make it dynamic for the final build to allow for easy editing of the questions.

Utilizing Vue.js

var looper = new Vue({
  el: "#quiz",
  data: {
    questionList: require("./js/questionsOptions"),
    currentQuestion: 0,
    ...
  }
});

questionOptions.js

module.exports = [
  {
    title: "Question 1",
    questionTitle: 'This is statement for Question 1',
    correctAnswer: true,
    answerSelection: [
      {
        name: "Answer 1 A",
        score: true
      },
      {
        name: "Answer 1 B",
        score: false
      },
    ]
  },
  {
    title: "Question 2",
    questionTitle: 'This is statement for Question 2',
    correctAnswer: true,
    answerSelection: [
      {
        name: "Answer 2 A",
        score: true
      },
      {
        name: "Answer 2 B",
        score: false
      }
    ]
  }
]

In the future, I anticipate needing to adjust the content or length of the question list within the final build. How can I accomplish this goal?

Answer №1

require() runs synchronously during the build process.

If you need to make an asynchronous request at runtime, you can utilize import(). Just remember that your application should be equipped to handle the asynchronous loading.

Here's an example:

data: {
  questionList: [],
  currentQuestion: 0,
},
async created () {
  this.questionList = await import(
    /* webpackChunkName: "questionOptions" */
    './js/questionsOptions'
  )
}

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

Using onchange within an onchange event will not function as intended

When I am in the process of creating 2 dropdown menus filled from a database, the issue arises when the second dropdown is generated after selecting a value from the first one. Upon choosing an option from the second dropdown, my ajax function is triggered ...

The Error message "Property 'data' is not present in Type <void> | AxiosHttpResponse<any>" is indicating that the data property is missing on

When I fetch data for a specific user, I have a promise that I use to setState. Below is the implementation: getUserUsername = (): string => { const { match } = this.props; return match.params.username; }; onFetchUser = () => getUse ...

Do devDependencies get installed when running `npm install -g my-package` command?

After browsing through this forum discussion, I found the answers a bit confusing and not directly addressing my concern. Therefore, I am posing a specific question: When using the command npm install -g my-package, are the dependencies listed under devDe ...

Positioning a designated div directly above a designated spot on the canvas

I'm grappling with a challenge in my game where the canvas handles most of the animation, but the timer for the game resides outside the canvas in a separate div. I've been struggling to center the timer around the same focal point as the squares ...

Wordpress team exhibition

Does anyone know how to create a Team showcase slider in Wordpress? I have been using slick slider, but I'm looking for a way to add team members easily through a plugin rather than manually. I found an image of what I want it to look like. Can any ...

Struggling to implement Google OAuth in a MERN stack - facing a 400 bad request error with the package @react-oauth/google

Here is the React form and relevant code sections for the issue: import { useGoogleLogin } from '@react-oauth/google'; const SignUpForm = () => { const navigate = useNavigate(); const [name, setName] = useState(""); const [email, setEm ...

Analyze the JSON data retrieved from the API endpoint to determine any

I am currently attempting to utilize axios to send an API request in order to validate login credentials, but I am facing difficulties retrieving the result from the API. The MongoDB .find function successfully locates the correct row, however, I am encoun ...

Is it possible to utilize the userId instead of the jwt token in this scenario?

Is it a good practice to hash the userId and store it in local storage, then send unhashed user id in authorization header on every route for server-side validation? Will this approach ensure security? ...

Sending Data Through Button from navBar in React-Native-Router-Flux

I have been working on a project that utilizes `react-native-router-flux` and I am facing a challenge in passing an object through `props`. Typically, I would use `Actions.someKey({ someProp: object })` for navigation. However, in this case, I need to navi ...

Tips for managing errors in HTTP observables

I'm currently facing a challenge with handling HTTP errors in an Angular2 observable. Here's what I have so far: getContextAddress() : Observable<string[]> { return this.http.get(this.patientContextProviderURL) .map((re ...

I can't understand why my server is displaying an error on the browser stating "This site can't be reached ERR_UNSAFE_PORT" while it is functioning flawlessly on the terminal

I have created an index.html file, along with index.js and server.js. In the server.js file, I have included the following code: const express = require("express"); const path = require("path" ); const app = express(); app.use(" ...

Pattern matching for ' ... '

I've been struggling to make a regular expression work properly: I need it to match anything that starts with __(' or __(" and ends with ') or ") I attempted using /__\(['"][^']*['"]\)/g and /__\([&apos ...

Feature to insert a fresh row into SAPUI5 table

I've been attempting to insert new rows into a SAPUI5 table with the click of a button. Despite watching numerous tutorials online, I haven't found one that fits my specific situation. Currently, the JSON data is loaded via a mock server with th ...

"Step-by-Step Guide: Activating Tab Functionality in J

I'm facing an issue here - I've been attempting to log the event's key code and I keep getting key number (9). I believe my script isn't disabling event.keyCode properly, hence the key function remains active. What changes should I make ...

"Embracing the power of Angular's scope

Currently working through a tutorial with Angular and utilizing this version of the framework: https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js[1] This is my current template setup: <div ng-controller="ParentController"> <div ...

The Jquery ajax page is redirecting automatically when a post request is made

Encountering an issue while attempting to upload multiple files through AJAX, as the process redirects to a blank page displaying only the names of the uploaded files. Here is the HTML tag: Below is the JavaScript function: function upload(){ var proje ...

NumericError on /post_create/ unrecognizable numeric value: 'manish'

I have a unique vision: I want to create posts with different authors in separate models def post_creation(request): author, initiated = Author.objects.get_or_create(name=request.user.username) form = CreationForm(request.POST or None , request.FILES or ...

The exact measurement of width is not specified in the custom element that extends HTMLCanvasElement

I have created a custom element that extends a canvas, but when I try to add it to the DOM, the width appears to be undefined. Here is my code snippet. class Renderer extends HTMLCanvasElement { constructor() { super(); } } customElements.def ...

Cordova encountered an error: Execution of inline script was denied due to violation of Content Security Policy directive

As I delve into the world of Cordova and jquery mobile, I encountered a perplexing error that reads: Refused to execute inline script because it violates the following Content Security Policy directive: "default-src 'self' data: gap: 'un ...

Guarantee the successful execution of a server-side function using my client-side function

I am currently in the process of creating a website that utilizes Javascript and Asp.net. My code contains numerous functions on the client side, within my html code, while my server side functions are called using a webservice. How can I ensure that my c ...