Skip to content

%PUBLIC_URL% not getting replaced during build while declaring @font-face in stylesheet #829

@anantzoid

Description

@anantzoid

I have a .ttf file under public/vendor/fonts/Roboto-Regular.ttf and I call it as:

@font-face {
    font-family: 'Roboto';
    src: url('%PUBLIC_URL%/vendor/fonts/Roboto-Regular.ttf');
}

The built file does not does not have the replaced string and thus, the font doesn't load. Is there something that I'm missing?

Activity

changed the title [-]`%PUBLIC_URL%` not getting replaced during build while declaring `@font-face` in stylesheet[/-] [+]%PUBLIC_URL% not getting replaced during build while declaring @font-face in stylesheet[/+] on Oct 3, 2016
gaearon

gaearon commented on Oct 3, 2016

@gaearon
Contributor

The %PUBLIC_URL% replacement only works in index.html.
If you need to reference anything from CSS in public, you can just use relative paths:

@font-face {
    font-family: 'Roboto';
    src: url('vendor/fonts/Roboto-Regular.ttf');
    /* assuming the file is in public/vendor/fonts */
}

In HTML, %PUBLIC_URL% is necessary because user may load any route, e.g. http://yourwebsiet.com/todos/42, and so we need to reference CSS file with an absolute path.

However assets in CSS will be resolved relative to that CSS so relative paths work.

Finally: I would not recommend using public folder for fonts and CSS. If you don’t have any specific reason for using it, I recommend importing CSS from JS instead. The user guide explains why:

Normally we encourage you to import assets in JavaScript files as described above. This mechanism provides a number of benefits:

  • Scripts and stylesheets get minified and bundled together to avoid extra network requests.
  • Missing files cause compilation errors instead of 404 errors for your users.
  • Result filenames include content hashes so you don’t need to worry about browsers caching their old versions.
locked and limited conversation to collaborators on Jan 22, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @gaearon@anantzoid

        Issue actions

          %PUBLIC_URL% not getting replaced during build while declaring @font-face in stylesheet · Issue #829 · facebook/create-react-app