When transitioning to the production environment, Nuxt.js fails to load images

I am currently working on developing a rather large app. Everything was running smoothly in the development environment without any errors. However, upon switching to the production environment, I started encountering numerous errors. Nuxt seems to be having trouble loading some of the images. The images are stored under assets/**/*.

Here is an example of how images are imported:

<img :src="require(~/assets/establishment_img/${image})" alt="preview image">

These are the errors: https://i.sstatic.net/SHbTB.png

nuxt-config.js

const path = require("path")

export default {
  // Global page headers: https://go.nuxtjs.dev/config-head
  head: {
    title: "Estudiant Orientation",
    htmlAttrs: {
      lang: "en"
    },
    meta: [
      { charset: "utf-8" },
      { name: "viewport", content: "width=device-width, initial-scale=1" },
      { hid: "description", name: "description", content: "" }
    ],
    link: [
      { rel: "icon", type: "image/x-icon", href: "/favicon.ico" },
      {
        rel: "stylesheet",
        type: "text/css",
        href:
          "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css"
      }, // font-awesome css
      ...
      
    ],
    script: [
      {
        hid: "stripe",
        src:
          "https://cdnjs.cloudflare.com/ajax/libs/Swiper/6.4.15/swiper-bundle.min.js",
        defer: true
      }, // swiper js
      ...
    
  },

  ...

  // Auto import components: https://go.nuxtjs.dev/config-components
  components: true,

  // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
  buildModules: [],

  // Modules: https://go.nuxtjs.dev/config-modules
  modules: [
    ...
  ],

  ...

  // Build Configuration: https://go.nuxtjs.dev/config-build
  build: {}
};

Additionally, this is what I have in my index.js for the server side:

// Handling Production
if (process.env.NODE_ENV === 'production') {
    // Static Folder
    app.use(express.static(__dirname + '/public/'));

    // Handle SPA
    app.get(/.*/, (req, res) => res.send(__dirname + '/public/index.html'));
}

Any suggestions on how to resolve this issue?

Answer №1

Avoid using

require(~/assets/establishment_img/${image})
in your nuxt.js application!

Simply place your static image in the /static/ directory at the root of your nuxt project and access it with this code:

<img :src="`/establishment_img/${image}`" alt="preview image">

This way, the image will be accessible in both development and production environments.

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

The loader fails to disappear even after the AJAX response has been received

I am currently working on a page that utilizes AJAX to display data. While the data is being fetched, I want to show a loading animation, and once the data has been retrieved, I want the loader to disappear. Below is a snippet of the code where I am attemp ...

What is the process for updating the source in an input box?

How can I use JavaScript to update the src value of an iframe based on input? <input class="url" id="url1" type="url" value="youtube url"> <input onclick="changevideo()" class="add-video" id="add-video1" type="submit" value="add to play ...

What is the best way to dynamically add a stylesheet using JavaScript/jQuery?

I've been scouring the web for a solution to a particular issue, but so far I'm coming up empty-handed. We're working with Umbraco CMS for a client's website, and it seems we can't insert conditional comments in the <head> se ...

Customizing Webpack 4's Entry Point

Below is the layout of my project: -node_modules -src -client -js -styles -views -index.js -webpack.config.js -server -.babelrc -package -package-lock -README.md -webpack ...

The Xero Node OAuth Authorize Callback URL is malfunctioning after granting access

When utilizing the xero-node library to produce a Request Token using the getRequestToken function, the URL provided does not automatically redirect the user to the designated callback address specified in the configuration. Instead, a screen displaying a ...

The window.open function is returning a null value after attempting to open the specified

Is there a way to prevent users from opening more than one IFrame window for my application? I have included the following code: <html> <head> <title>Testing Window Opening Limitation</title> <meta http-equiv="Content-Type" cont ...

Using Node-twitter within the Express framework

I'm currently exploring the node-twitter module within the express framework. Although I have a basic understanding of node, including routing, rendering jade templates, and installing packages, I find myself overwhelmed by the sheer number of package ...

Top spot for locating resolve functions in AngularJS

I'm currently in the process of setting up resolves for my admin panel routes and I'm pondering the best way to store them without cluttering my router with methods. Here's what I have so far: when('/admin', { templateUrl: &ap ...

Error: Unable to process reduction on ships - function "reduce" is not functional

I created a boat visualization tool using a specific API. The API responds with a JSON that I then inject into a table. The issue: At times during the day, I observed the application would abruptly stop functioning and throw an error: Unhandled Rejection ...

Ways to use jQuery to disable row form elements in the second and third columns

I need a way to deactivate form elements in the second and third columns, starting from the second row until the nth row using a jQuery selector. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/> ...

Issue with manipulating currency conversion data

Currently, I am embarking on a project to develop a currency conversion application resembling the one found on Google's platform. The main hurdle I am facing lies in restructuring the data obtained from fixer.io to achieve a similar conversion method ...

Obtaining a JSON reply using Ember

Exploring new possibilities with Ember js, I am eager to switch from fixtures to using an API. Below is the code I have implemented to fetch the data: App.ItemsRoute = Ember.Route.extend({ model: function() { return $.getJSON('http://som ...

Calculate the difference and sum of time values with varying signs in JavaScript

-12:00 - 5:30 => -6:30 -2:00 - 5:30 => 3:30 00:00 - 5:30 => -5:30 6:00 - 2:30 => 3:30 I am interested in subtracting time with both positive and negative indices. let myCountries = [ { countryName: "NewZealand", ...

What could be causing my React component to only render after pressing ctrl + shift + R?

I am facing an issue with my chrome extension where it only appears after refreshing the page using ctrl + shift + r. However, there is a new problem that arises when I click on a link that refreshes the page, causing the extension to disappear and requiri ...

Creating a worldwide directive using AngularJS

I'm currently working on implementing a directive that will manage user interaction with the navigation system on my website. The directive includes an element.click event listener in the link function, which is responsible for toggling the display of ...

Comparing Pinia and useState() in Nuxt 3

Choosing Between Store (Pinia) and UseState When it comes to deciding between useState and a store like Pinia, the question arises - can useState replace any store such as Pinia? With useState allowing ref sharing across all components, determining whethe ...

Encountering a Javascript error while trying to optimize bundling operations

After bundling my JavaScript with the .net setting BundleTable.EnableOptimizations = true;, I've encountered a peculiar issue. Here's the snippet of the generated code causing the error (simplified): var somVar = new b({ searchUrl: "/so ...

The tagging feature in ui-select isn't working properly, showing an error message that says "Cannot read property 'length' of undefined"

Looking to set up a ui-select for keyword tagging. Initially, when adding a new tag everything works fine, but after removing all tags and adding a new one, I get the error: Cannot read property 'indexOf' of undefined Check out the demo here ...

Prevent time slots from being selected based on the current hour using JavaScript

I need to create a function that will disable previous timeslots based on the current hour. For example, if it is 1PM, I want all timeslots before 1PM to be disabled. Here is the HTML code: <div class=" col-sm-4 col-md-4 col-lg-4"> <md ...

An inquiry regarding props in JavaScript with ReactJS

Check out the following code snippet from App.js: import React from 'react' import Member from './Member' function App () { const members = [ { name: 'Andy', age: 22 }, { name: 'Bruce', age: 33 }, { n ...