Welcome to our comprehensive guide on JSON Import in Vite JS! In this tutorial, we'll dive deep into understanding how to work with JSON files in Vite, a modern and fast-growing front-end build tool. By the end of this lesson, you'll be able to import JSON data into your Vite projects and leverage it for real-world applications. 🎯
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is a text format that is completely language independent but uses conventions that are familiar to programmers who use C-family languages.
JSON is a versatile data format that can be used to store and transport data between a server and a client (like a web browser). In Vite, JSON files are often used to store configuration data, data from APIs, or even predefined data structures for your application.
Before we dive into JSON imports, let's quickly set up a new Vite project:
npm install -g vitevite create my-appcd my-appviteNow that we have our Vite project set up, let's learn how to import JSON files:
src folder: touch src/data.json{
"name": "John Doe",
"age": 30,
"hobbies": ["Reading", "Gaming", "Coding"]
}// src/main.js
import { defineConfig } from 'vite'
import { fileURLToPath } from 'url'
import { readFileSync } from 'fs'
// Import JSON data
const data = JSON.parse(readFileSync(fileURLToPath(import.meta.url, '../data.json')))
console.log(data)viteYou should now see the data from the JSON file printed to the console.
Let's take it a step further and create a simple web page that displays data from our JSON file:
App.vue file in the src folder: touch src/App.vue<template>
<div>
<h1>Personal Info</h1>
<ul>
<li>Name: {{ name }}</li>
<li>Age: {{ age }}</li>
</ul>
<h2>Hobbies</h2>
<ul>
<li v-for="hobby in hobbies">{{ hobby }}</li>
</ul>
</div>
</template>
<script>
// Import JSON data
import data from '../data.json'
export default {
data() {
return {
name: data.name,
age: data.age,
hobbies: data.hobbies
}
}
}
</script>main.js file to use the Vue app:import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')index.html file to include the Vue app:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My Vite App</title>
</head>
<body>
<div id="app">
<!-- Vue app will be rendered here -->
</div>
<!-- Imported Vue and Vite scripts -->
<script type="module" src="/src/main.js"></script>
</body>
</html>viteNow, when you open your browser and navigate to http://localhost:5000, you should see the personal information and hobbies displayed from the JSON data.
What is the purpose of JSON files in Vite JS?
That's it for our JSON Import tutorial in Vite JS! With the knowledge you've gained today, you're ready to take on real-world projects and leverage JSON data in your Vite applications. Happy coding! 💡🎯💻