Static font files not served in Vite dev environnement

Viewed 33

I am trying to switch from webpack to vite in an existing Laravel application. For local development I use Laravel Valet.

If I run vite build everything works correctly (images, fonts, scss), but if I run vite the only bug I get is that it doesn't get the fonts path correctly (Error 404):

https://example.test:5173/fonts/open-sans/regular-400.woff2

Without the port it would work.

I've read a lot and I think I've tried everything:

Attempts (failed) in the Vite configuration:

export default defineConfig(({ command, mode }) => {

    return {
        // root: './',
        // base: './',
        // publicDir: 'public',
        // assetsInclude: ['public/fonts'],

        // Rest of the configuration are Plugins (Laravel, Vue), Alias etc...            
    }
});

So I try to change the root, base, publicDir nor assetsInclude and don't remember what else... and nothing of them hasn't solved my problem.

The structure of my public folder:

- public
  - build
    - assets
  - fonts
  - images

css font-face:

@font-face {
    ...
    url('/fonts/open-sans/regular-400.woff2') format('woff2'),
    url('/fonts/open-sans/regular-400.woff') format('woff');
}
1 Answers

The solution I found was to add the alias for the font path (public/font) only in the dev environment:

export default defineConfig(({ command, mode }) => {

    const alias = {
       (some alias),       
    };

    // dev environment
    if (command === 'serve') {
        Object.assign(alias, { '/fonts': path.resolve(__dirname, 'public/fonts') });
    }
    
    return {
        ...
        resolve: {
            alias
       }
    }
});

I think it's a Vite bug and I don't know if that's the best solution for that, so I'm open to any suggestions.

Related