Skip to main content

Command Palette

Search for a command to run...

./public or ./src/assets ?

Updated
2 min read

There are two place to put resources that would be later imported into a react project, src/assets/ folder and public/ folder. So what is the diff?

  1. Build Processing
  • src/assets: Files will be processed by build tools (like webpack, Vite)

    • Images may be compressed and optimized

    • CSS/SCSS will be compiled and prefixed

    • Filenames will be hashed, e.g., logo.pnglogo.a5d4f.png, for cache control

    • Filename caching is critical for updates, since the browser would cache the resource. If the browser find no changes on the name, it would not fetch the updated version, through giving them a hash name it is easier to do cache control and version control.

  • public: Files will be copied to their build directory as-is

    • No compression or optimization
  • Filenames remain unchanged

  • Suitable for files that need fixed paths

  1. Usage Method
  • src/assets: Need to be imported
import logo from '@/assets/images/logo.png'
  • public: Referenced directly via absolute path
<img src="/images/logo.png" />
  1. Use Case Examples: Files to put in public:
  • favicon.ico

  • robots.txt

  • sitemap.xml

  • Resources that need to be referenced directly in index.html

  • Files that require fixed access paths

  • Large media files (like videos) that don't need build processing

Files to put in src/assets:

  • Images used by components

  • Style files

  • Other resources that need build tool processing

  • Files that need frequent modifications

In simple terms, if a resource needs to be processed by build tools or changes frequently, put it in src/assets; if it needs to remain unchanged with a fixed path, put it in public.

Here is a sample of using Vite’s plugin to optimize & compress the image.


// vite.config.js
import { defineConfig } from 'vite'
import imagemin from 'vite-plugin-imagemin'

export default defineConfig({
  plugins: [
    imagemin({
      // WebP conversion
      webp: {
        quality: 75
      },
      // PNG compression
      pngquant: {
        quality: [0.8, 0.9],
        speed: 4
      },
      // JPEG compression
      mozjpeg: {
        quality: 75
      }
    })
  ]
})