1

I move from CRA to Vite.

I am using an external component library that is using some internal assets (images and fonts). Before moving from CRA everything was working fine, but now Vite is not loading the images in development mode.

I'm getting 404 errors.

console error logs

It's trying to load them from node_modules/assets but the assets are placed in node_modules/component-library/dist/assets

Once I do the build I have no issues. All the files are copied correctly into the asset folder.

I'm not using directly the assets in my code. The assets are being used by the library internally. I'm just using a component from the library which is using these internal assets.

This is my configuration file:

/// <reference types="vitest" />
import { defineConfig } from 'vite'
import { configDefaults } from 'vitest/config'

import * as path from 'path'
import react from '@vitejs/plugin-react'
import viteTsconfigPaths from 'vite-tsconfig-paths'
import svgrPlugin from 'vite-plugin-svgr'

// https://vitejs.dev/config/
export default defineConfig({
  base: '/',
  server: {
    open: true,
    port: 3000,
  },
  plugins: [
    react(),
    viteTsconfigPaths(),
    svgrPlugin({
      svgrOptions: {
        svgProps: { role: 'img' },
        titleProp: true,
        descProp: true,
      },
    }),
  ],
  resolve: {
    alias: [{ find: '^@/', replacement: path.resolve(__dirname, 'src/') }],
  },
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: './test-setup.ts',
    coverage: {
      reporter: ['text', 'html'],
      exclude: ['./node_modules/', './test-setup.ts', './dist/', './build/'],
    },
    exclude: [...configDefaults.exclude, 'build', 'ssl', 'coverage'],
    include: ['./src/**/*.{test,spec}.{ts,tsx}'],
  },
})

I tried to add the library to optimizeDeps but it still not working.

Priyen Mehta
  • 1,096
  • 1
  • 5
  • 19
hjaraba
  • 21
  • 4
  • What is your question? You indicate that once you do the build, your problem is solved. So...it seems like that's your solution. – Trott May 10 '23 at 01:48
  • Hello, thanks for answering, the problem is that the assets are not being loaded when I work in development mode using vite or vite serve. – hjaraba May 10 '23 at 06:20

1 Answers1

1

As a workaround I ended adding vite-plugin-static-copy and copying the assets where vite expect to found them:

viteStaticCopy({
      targets: [
        {
          src: 'node_modules/@organisation/component-library/dist/assets/*',
          dest: 'node_modules/assets',
        },
      ],
    }),

is there a way to tell Vite to look in the corresponding path (@organisation/component-library/dist/assets/) for that library?

it is trying to access this path in the css:

url("http://localhost:3000/node_modules/assets/mask-c6a253a6.svg")

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
hjaraba
  • 21
  • 4