1

I have a simple client-side page, made with React using Vite.

The project worked perfectly when running localy (npm run dev), but after running npm run build, a dist folder is created and that's the one I use for Firebase hosting. The problem is, all the fetch (to internal .json files) and src={} do not work:

GET https://webpage.web.app/src/imgs/icons/icon.png 404 (Not Found)
GET https://webpage.web.app/src/data/items.json 404 (Not Found)

which is a huge problem since I need dynamic imports for my components like this:

<img src={item.machineImg} alt="imgMachine" />

Image and JSON imports do work using import theThing from 'path/to/the/thing.json' at the start of the scripts.

Could this be a problem with path not properly converting when building? or is there something I have to configure with Vite?

My vite.config.js:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()]
});

My structure

I tried to change as many <img src="/path/to/img.png" /> by first importing with import theThing from 'path/to/the/thing.png' as possible, but I really need dynamic imports like this: <img src={item.machineImg} alt="imgMachine" />

4
  • If you're not importing those JSON and image files, are they even in dist/? Shouldn't they be in public/?
    – jonrsharpe
    Commented Jul 3 at 19:02
  • No, my data files are in a "src" folder. I do not have a "public" folder. I'm kind of new to this, and I'm not sure about the correct structure of the files. If I move my index.html or the .json or imgs Vite won't compile for some reason. Commented Jul 3 at 22:25
  • Thanks, but I got "Assets in public directory cannot be imported from JavaScript. If you intend to import that asset, put the file in the src directory, and use /src/data/items.json instead of /public/data/items.json." Commented Jul 3 at 22:35

1 Answer 1

1

First ensure the public Directory for static files like images and add the public dir. to the root folder. Update JSON file paths to reference the public directory.

Try configuring your vite config file for importing dynamically,

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@imgs': '/public/imgs',
      '@data': '/public/data'
    }
  }
});

Dynamic imports in React:

<img key={index} src={item.machineImg.replace(/^\/src\//, '@imgs/')} alt="imgMachine" />

Not the answer you're looking for? Browse other questions tagged or ask your own question.