How To Use Local Static Images In Svelte?
Last Updated :
16 Aug, 2024
Static images are stored locally within your project and can be accessed directly through the file path. In Svelte, you can use these static images in your components by importing them directly or referencing their paths within the public directory.
In this article, we will explore two different approaches to using local static images in Svelte.
Steps To Use Local Static Images In Svelte
Step 1: Install Node.js
Make sure Node.js is installed on your machine. You can download it from nodejs.org.
Step 2: Install Svelte
Open your terminal and run the following command to set up a new Svelte project:
npx degit sveltejs/template svelte-app
Step 3: Navigate to Your Project Directory
Change to the newly created project directory:
cd svelte-app
Step 4: Install Dependencies
Install the required npm packages:
npm install
Project Structure
Folder StructureDependencies
"devDependencies": {
"@rollup/plugin-commonjs": "^24.0.0",
"@rollup/plugin-node-resolve": "^15.0.0",
"@rollup/plugin-terser": "^0.4.0",
"rollup": "^3.15.0",
"rollup-plugin-css-only": "^4.3.0",
"rollup-plugin-livereload": "^2.0.0",
"rollup-plugin-svelte": "^7.1.2",
"svelte": "^3.55.0"
},
"dependencies": {
"sirv-cli": "^2.0.0"
}
Approach 1: Using Static Asset Paths
In this approach, we are using static asset paths to reference images stored in the public directory of the Svelte project. By directly assigning the image paths to the src attribute, the images can be dynamically swapped when a button is clicked, allowing for interactive content within the application.
Example: The below example uses Static Asset Paths to Load Static Images in Svelte.
JavaScript
<!-- App.svelte -->
<script>
let currentImage = "/images/image1.png";
let imageName = "Image 1";
function changeImage() {
if (currentImage === "/images/image1.png") {
currentImage = "/images/image2.jpg";
imageName = "Image 2";
} else {
currentImage = "/images/image1.png";
imageName = "Image 1";
}
}
</script>
<h1>GeeksforGeeks</h1>
<h3>Approach 1: Using Static Asset Paths</h3>
<div class="container">
<p>Current Image: {imageName}</p>
<img src={currentImage} alt="Dynamic Image" />
<button on:click={changeImage}>Change Image</button>
</div>
<style>
h1 {
color: green;
text-align: center;
}
h3 {
text-align: center;
}
.container {
text-align: center;
margin-top: 20px;
}
img {
max-width: 300px;
height: auto;
display: block;
margin: 0 auto;
}
button {
margin-top: 20px;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
</style>
Output:
How To Use Local Static Images In Svelte
Approach 2: Using src Binding
In this approach, we are using the src attribute binding in the <img> tag to dynamically display images based on the user's selection from a dropdown menu. The src is bound to the selectedImage variable, which updates whenever the user selects a different image, allowing for interactive image switching within the application.
Example: The below example uses src Binding to use local static images in Svelte.
JavaScript
<!-- App.svelte -->
<script>
const images = [
{ name: "Image 1", path: "/images/image1.png" },
{ name: "Image 2", path: "/images/image2.jpg" },
];
let selectedImage = images[0].path;
let imageName = images[0].name;
function updateImage(event) {
const selectedOption = event.target.value;
const image = images.find((img) => img.name === selectedOption);
selectedImage = image.path;
imageName = image.name;
}
</script>
<h1>GeeksforGeeks</h1>
<h3>Approach 2: Using `src` Binding</h3>
<div class="container">
<p>Selected Image: {imageName}</p>
<img src={selectedImage} alt="Dynamic Image" />
<select on:change={updateImage}>
{#each images as image}
<option>{image.name}</option>
{/each}
</select>
</div>
<style>
h1 {
color: green;
text-align: center;
}
h3 {
text-align: center;
}
.container {
text-align: center;
margin-top: 20px;
}
img {
max-width: 300px;
height: auto;
display: block;
margin: 0 auto;
}
select {
margin-top: 20px;
padding: 10px;
font-size: 16px;
cursor: pointer;
}
</style>
Output
How To Use Local Static Images In Svelte
Similar Reads
How to use SVG Images in HTML?
SVG images are special graphics used in HTML that doesnât lose quality when resized. They are great for icons, logos, and shapes because they stay clear at any size. To use SVG images in HTML, add them with <img src=" image.svg"> or paste SVG code directly with <SVG>.1. Using SVG Image w
2 min read
How To Optimize Images in Vite Projects?
Optimizing images is an important step in improving the performance of your web projects, and Vite, being a modern front-end build tool, makes it easy to simplify this process.Image optimization reduces file sizes, resulting in faster load times, better user experience, and improved SEO rankings. Th
3 min read
How to Use Local Docker Images With Minikube?
Minikube is a software that helps in the quick setup of a single-node Kubernetes cluster. It supports a Virtual Machine (VM) that runs over a docker container and creates a Kubernetes environment. Now minikube itself acts as an isolated container environment apart from the local docker environment,
7 min read
How to Cache Images in React Native?
Caching images in React Native enhances app performance by reducing network load and improving image load times. By storing frequently accessed images locally, the app can quickly display them without needing to re-download, resulting in a smoother and faster user experience. Caching images in React
2 min read
How to Persist Svelte Store?
To persist a Svelte store, you can synchronize its state with browser storage like 'localStorage' or 'sessionStorage'. On component mount, retrieve the stored value and initialize the Svelte store with it. Set up a subscription to the store that updates the browser storage whenever the store's state
3 min read
How to import image in Next.js ?
Next.js is a full-stack React-based framework. Unlike a traditional react app, which loads and renders the entire application on the client, Next.js allows the first-page load to be rendered by the server, which is great for SEO and performance. Some of the key features of Next.js are:Â Server-side
4 min read
How to display local image in React Native Application ?
In this article, we will learn to display an image from a phone gallery in a React Native application. We will use react-native-image-picker to select the image and display it in our application. You can find the API reference for this package at the end of this article.Step 1: To initialize a new R
3 min read
How to Lazy Load Images in Android ListView?
Many times, the UI of an application gets blocked while downloading images from the internet. This problem can be solved by implementing lazy loading of images in the list view while displaying the text. It is a strategy to identify resources as unimportant and load them only when needed. It's a way
3 min read
How to Make an SVG Image in JavaScript ?
The SVG images are vector images that do not lose their quality either in the case of Zoom in or Zoom out. These are the Scalable Vector Graphics that can be directly created using the <svg> tag in HTML or dynamically using JavaScript. Let us create an SVG using JavaScript. We can use the belo
2 min read
How to Add Image in Ruby on Rails?
In Ruby on Rails, there are several ways to add images to your application. In this article, we will see one of the common methods which is using an assets pipeline.Steps on How to Create a ProjectStep 1: Create a demo project using the command below. It will create a project named 'myapp' in the cu
2 min read