How can I import an image file dynamically in Nuxt.js using environmental variables?

// env.development.js

module.exports = {
  fileName: 'logo_dev.png'
}

// env.production.js

module.exports = {
  fileName: 'logo_prod.png'
}

// index.vue

<script>
import logoSrc from '@/assets/images/' + process.env.fileName

export default {
  data () {
    return {
      logo: {
        src: logoSrc,
      }
    }
  },
</script>

Hey there, I'm exploring Nuxt js and facing a challenge. I want to dynamically import an image file based on the environment value when building it. Unfortunately, I encountered an error with the following code snippet.

import logoSrc from '@/assets/images/' + process.env.fileName

Is there a way to dynamically import an image file using an env variable? If so, do you know of any helpful solutions or workarounds? Thanks in advance!

Answer №1

Absolutely!

Just follow these instructions:

1 - Set up your variable in a .env file:

CAR=mustang

2 - Include the environment variable in your vue.config.js file:

{
  publicRuntimeConfig: {
    carType: process.env.CAR
  },
}

3 - Use it in your Vue component:

<img
  :src="require(`~/assets/images/${$config.carType}.jpg`)"
  style="width: 300px; height: 200px"
/>

Check out this code sandbox for reference: https://codesandbox.io/s/vuejs-load-image-dynamically-with-environment-variable-abc123

Enjoy experimenting! :)

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

Deliver an extensive JSON reply through a Node.js Express API

When dealing with a controller in a node/express API that generates large data sets for reports, reaching sizes as big as 20Mb per request, maintaining a positive user experience becomes essential. What strategies can be employed to efficiently handle suc ...

Utilizing SVG images as interactive elements without embedding them directly into the HTML code

I am facing a challenge with incorporating button images saved as svgs into my HTML site. These images are intricate, so I prefer to have them stored separately as .svg files rather than directly within the HTML file. Additionally, the buttons are circular ...

Activate the drop-down menu in Angular 6 by hovering over it with your mouse

I am just beginning my journey with Angular 6 and Bootstrap. Currently, I am working on a Navigation bar that consists of 3 navigation items. One of the nav items is called "Store", and when a user hovers their mouse over it, I want to display a mega menu ...

What is the best way to render images on the server side in React?

I've got this snippet of code residing in my server/server.js import path from 'path'; import fs from 'fs'; import React from 'react'; import ReactDOMServer from 'react-dom/server'; import express from 'ex ...

having trouble transferring data from one angular component to another

I've been attempting to send data from one component to another using the service file method. I've created two components - a login component and a home component. The goal is to pass data from the login component to the home component. In the l ...

Utilize CountUp.js to generate a dynamic timer for tracking days and hours

I am looking to create a unique counter similar to the one featured on this website https://inorganik.github.io/countUp.js/ that counts up to a specific number representing hours. My goal is to display it in a format such as 3d13h, indicating days and hour ...

Use Ramda to convert an array of objects into nested objects

As a beginner, please forgive me for asking what may be considered a naive question. I currently have an array of objects const arr = [{id: 1, name: 'Pete'}, {id: 5, name: 'John'}, {id: 3, name: 'Peter'}] and I am looking to ...

Manipulating arrays of objects using JavaScript

I am working with an array of objects represented as follows. data: [ {col: ['amb', 1, 2],} , {col: ['bfg', 3, 4], },] My goal is to transform this data into an array of arrays like the one shown below. [ [{a: 'amb',b: [1], c ...

What is the best way to access the image source attribute within a directive?

Here's a straightforward image directive example: (function () { 'use strict'; angular .module('myapp') .directive('imageTest', imageTest); function imageTest() { var directive = { ...

Tips on leveraging state values within the makeStyles function in Material UI React

I'm in the process of building a Webpage and incorporating Material UI for the Components. Here's the code: import { makeStyles, Typography } from "@material-ui/core"; const useStyles = makeStyles((theme) => ({ container: { ...

Tips for storing arrays in AngularJS with JavaScript

I am new to using JavaScript. I have a function that stores objects in an array to an Angular model. Here is an example: function getSpec(){ debugger var i; for(i=0;i<main.specifications.length;i++){ main.newProduct.Specification= ( ...

Updating a Vuetify 3 Theme on the Fly

I am looking to dynamically switch themes. I have defined a lightTheme and darkTheme. export default createVuetify({ theme: { defaultTheme: "lightTheme", themes: { lightTheme: { dark: false, colors: { pri ...

Animating progress bars using React Native

I've been working on implementing a progress bar for my react-native project that can be used in multiple instances. Here's the code I currently have: The progress bar tsx: import React, { useEffect } from 'react' import { Animated, St ...

Display the current time and continuously update it in real-time on the DOM using React

Incorporating a live clock feature into my app is important to me. I want the time to update automatically, without requiring the user to manually refresh the page. My goal is to have a clock display the time, for example 11:59, and then transition to 12: ...

What is the best way to handle the resolution of multiple promises as they complete?

Suppose I have three different promises each taking a varying amount of time to resolve - 1000ms, 2000ms, and 3000ms respectively. How can I simultaneously start all the promises and handle them as they get resolved? For instance: let quickPromise = new ...

I'm having trouble inserting my object into the scene: THREE.Object3D.add: the item is not a valid instance of THREE.Object3D

Recently, I started using three.js. Initially, I utilized a JSON file for my 3D model but encountered issues when exporting it from Blender. To resolve this, I decided to switch to obj files. Although the new obj model is working fine, I am struggling with ...

Utilizing radio buttons to toggle the visibility of multiple content sections

In order to determine which P's display on a page, I need to utilize three radio buttons. The items are fetched from a dynamic database, making the process flexible as there is no fixed number of items. Ideally, I would prefer to stick with JavaScript ...

What is the reason that Gatsby's arrow function is unable to access a value from props that is calculated from a promise?

Could someone shed light on why the key value is showing as undefined within the arrow function: // in parent component const Parent = () => { const [key, setKey] = useState<string>(); // this contains an expensive function we on ...

Retrieving user data using axios in React to fetch user_id information

I'm currently working on a React project where I have created a simple list and I am fetching data using axios. Here's a snippet of my code: https://codesandbox.io/s/old-worker-6k4s6 import React, { useState, useEffect } from "react"; ...

Extracting information from an ENORMOUS Array

Let's start with my code snippet, featuring an array: var UserProfiles = [{ userProfileID: 1, firstName: 'Austin', lastName: 'Hunter', email: 'test', token: '', platform: 'android ...