Search code examples
cssreactjssasscreate-react-app

how to access Node JS "homepage" or PUBLIC_URL value in CSS?


I want to host my React App on IIS under a subfolder of my website. I have setup homepage in package.json

{
    "homepage": "/MyApp"
}

my app working fine, however, I have one issue from my SCSS: my public/fonts folder and public/images folder are getting from website root folder, not in MyApp sub-folder

from website root

http://myhost.com/fonts/MavenPro-Regular.ttf
http://myhost.com/images/myIcon.png

not my expected

http://myhost.com/MyApp/fonts/MavenPro-Regular.ttf
http://myhost.com/MyApp/images/myIcon.png


I am using `create-react-app`, the top component `App.jsx` import `App.scss` ```js import './App.scss'; ```

in App.scss, import variables.scss like this:

@import "./themes/generated/variables.base.scss";
.my-icon-class {
    background: url('/images/myIcon.png') no-repeat;
    background-size: contain;
}
......

in variables.scss, I have a font variable which src point to fonts folder located in public\fonts
and CSS class background: URL()

@font-face {
  font-family: 'MavenPro-Regular';
  src: url('/fonts/MavenPro-Regular.ttf');
  font-weight: 400;
  font-style: normal;
}

Is there something I am missing? Is there a PUBLIC_URL variable I can use in SCSS?

A colleague told me to move fonts and images folder into src folder, then change all URL from URL('/fonts/...') to URL('fonts/...') but I think it may be not a good structure (or I am wrong?). I hope to find out what's wrong in my setting.


Solution

  • My previous understanding of Public folder's usage is wrong, I should put fonts and images into src folder, let them bundled into static folder, instead of letting them direct copy into the build folder:
    https://create-react-app.dev/docs/using-the-public-folder/

    For CSS file, fonts and image should reference to an absolute path, so I should not reference the source to the public folder:
    https://github.com/facebook/create-react-app/issues/829

    That's the reason why I should move my fonts and images files into src folder for bundling.