atellmer / dark

The lightweight and powerful UI rendering engine without dependencies and written in TypeScript💫 (Browser, Node.js, Android, iOS, Windows, Linux, macOS)
MIT License
41 stars 1 forks source link

Importing fonts with styled: file urls on server #60

Closed einar-hjortdal closed 5 months ago

einar-hjortdal commented 5 months ago

Using Bun and SSR on Bun, as usual according to my starter template

import SomeFontNameRegular from '../assets/fonts/SomeFontNameRegular.woff2'
const GlobalStyle = createGlobalStyle`
@font-face {
  font-family: 'SomeFontName';
  font-weight: normal;
  font-style: normal;
  font-display: swap;
  src: url(${SomeFontNameRegular}) format('woff2');
}
html,
body {
  font-family: 'SomeFontName';
}`

const Root = component(({ slot }) => {
  return (
    <>
      <GlobalStyle />
      {slot}
    </>

This results in a not found error: the server responds with this

        <style dark-styled="g">
            @font-face {
                font-family: 'SomeFontName';
                font-weight: normal;
                font-style: normal;
                font-display: swap;
                src: url(/home/coachonko/Documents/projects/frontend/dark-website/src/assets/fonts/SomeFontNameRegular.woff2) format('woff2');
            }

            html, body {
                font-family: 'SomeFontName';
            }
        </style>

As you can see the url is resolved as an absolute path. Bun imports the file as an asset and the file name is SomeFontNameRegular-hash.woff2 and it is placed in the build directory.

The correct file is imported anyway because the correct url is resolved on the browser.

@font-face{font-family:'SomeFontName';font-weight:normal;font-style:normal;font-display:swap;src:url(/_dark/SomeFontNameRegular-1b44130d820257be.woff2) format('woff2');}html,
body{font-family:'SomeFontName';}

Is this expected?

As a workaround, I can put the font files in the public directory of my project and use absolute URLs instead of importing the files as assets with bun. Note the public directory in the starter template works like a nextjs / vite public directory.

einar-hjortdal commented 5 months ago

I am assuming this is expected. When using SSR the correct way to import fonts is to use absolute paths for files on the same server, or urls for files on remote servers. Closing

atellmer commented 5 months ago

styled components does absolutely nothing related to paths, it is the programmer's responsibility to provide the correct path to resources.