How add not imported image to output build with vite?

Viewed 721

I have an app folder with some images that are used by the external script and I need to include those images in the dist build folder.

I tried to log files that go to output and those images are not included. I tried to add assetsInclude property but seems that property is not for that purpose.

How can I include some specific images in dist folder that aren't imported explicitly ? Here is my vite.config.js file.

import { resolve, parse } from 'path';
import { defineConfig } from 'vite';

export default defineConfig({
  base: '/',
  root: resolve(__dirname, 'app'),

  assetsInclude: ['/app/images/externalImage.png'],

  build: {
    emptyOutDir: true,
    
    rollupOptions: {
      output: {
        dir: './dist',
        assetFileNames: (asset) => {
          console.log(parse(asset.name).name);
          if (parse(asset.name).name === 'externalImage') {
            return "images/src/[name][extname]";
          }
          return "assets/[name].[hash][extname]";
        }
      },
    },
  },
});

1 Answers

In my js file which is included as a module inside the HTML file, I added string that you can see below. Here is details of how to expose the current module URL.

app/js/app.js

new URL("../images/src/externalImage.png", import.meta.url);

Also changed a bit config - added outDir prop:

import { resolve, parse } from 'path';
import { defineConfig } from 'vite';

export default defineConfig({
  base: '/',
  root: resolve(__dirname, 'app'),

  build: {
    outDir: '../dist',
    emptyOutDir: true,
    
    rollupOptions: {
      output: {
        assetFileNames: (asset) => {
          if (parse(asset.name).name === 'externalImage') {
            return "images/src/[name][extname]";
          }
          return "assets/[name].[hash][extname]";
        }
      },
    },
  },
});
Related