Search code examples
reactjsimagenext.jsshared-librariesnx-workspace

React library component bg-image not found when used in Nextjs app in Nx monorepo


My React library component does not find its background image, when used in my Next.js app (both live in my Nx workspace).

Console: localhost:4200/images/svg/Background.svg 404 (Not Found)

Documentation doesn't tell anything useful, and I've been googling for hours, no working solution found. Why does something that should kinda be working out of the box seem so hard, what am I missing?

I'm running the latest version of Nx workspace: 15.9.2

Inside the Nx monorepo I have:

  • app1 (nextjs w tailwindcss)
  • ui-lib (react ui components library using tailwindcss)

Library:

  • react components: src/lib
  • images: public/images/svg

How ui lib components use their bg-images (TailwindCSS):

bg-[url('/images/svg/Background.svg')]

App's tsconfig.json "paths":

"paths": {
  "@ui-lib": ["libs/ui-lib/src/index.ts"]
},

Don't the public/* contents of the library get merged with and served by nx serve app1 or something?


Solution

  • Figured it out:

    • place images in libs/library-name/assets/images/... (public works too)
    • set svgr: true in next.config.js of the app (restart nx serve after this)
    • import SVG images to library components like this:

    import Background from '../../assets/images/svg/Background.svg'

    Don't use TailwindCSS to set the background, instead set it the casual React way:

    style={{ backgroundImage: url(${Background}) }}