Search code examples
javascriptvite

Vite on build does not copy images


I noticed that when using images without the src attribute, it does not copy images on build to dist folder

<img class="lozad" data-src="/src/assets/img/logos/...

js folder inside assets folder in file explorer

My vite config:

import { fileURLToPath, URL } from "node:url";
import { resolve } from "path";

import { defineConfig } from "vite";

// https://vitejs.dev/config/
export default defineConfig(({ command, mode, ssr }) => {
  return {
    base: "",
    server: {
      port: 3000,
      open: true,
    },
    build: {
      outDir: "dist",
      assetsDir: "assets",
      sourcemap: true,
      minify: true,
      emptyOutDir: false,
      rollupOptions: {
        input: {
          index_page: resolve(__dirname, "index.html"),
          super_page: resolve(__dirname, "templates/super.html"),
          blog_page: resolve(__dirname, "templates//blog.html"),
        },
        output: {
          chunkFileNames: "assets/js/[name].js",
          entryFileNames: "assets/js/[name].js",
          assetFileNames: ({ name }) => {
            if (/\.(gif|jpe?g|png|svg)$/.test(name ?? "")) {
              return "assets/img/[name].[ext]";
            }

            if (/\.css$/.test(name ?? "")) {
              return "assets/css/[name].[ext]";
            }
            return "assets/[name].[ext]";
          },
        },
      },
    },
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
      },
    },
  };
});

I don't know how to fix this. Do I need to add another prefix to the image processing or something like that? I didn't find anything like this in the documentation.

UPD: I don't want to use the public folder


Solution

  • The proper solution for this would be "Custom html attributes resolving". As of writing this answer, the issue is still open, with a not yet merged PR addressing it.

    So for now, I would recommend finding a workaround such as