Home > Software engineering >  react-scripts include images from npm package
react-scripts include images from npm package

Time:08-20

I created an NPM package that uses images inside it's scss file for displaying a 404 page. The images are included via background-image: url('./img.png') and loads just fine when developing locally.

This package in bundled with webpack and has the images added to the dist folder of that package.

When I install the package in my react project (that was initialized with create-react-app) the images are visible in that package like so:

 - package-name
   - dist
     - components
        ...
     index.js
     img.png

When testing my application locally via react-script start the image url for this component shows localhost:3000/static/js/img.png in the Styles tab of the web tools. I then ran react-script build to see what the output would be but the only files in build/static/js are main.af1d83e2.js and its LICENSE and map files.

What do I need to do so that the images from my package will be loaded correctly when referencing the component from my local project.

The react code looks something like this, unfortunately the package is hosted on a private NPM registry so I can not give you a working example of my issue. The component and it's styling are loading correctly the only issue is the images are not able to be found.

import { PageNotFound } from 'package-name';

<BrowserRouter>
  <Routes>
    <Route index element={<h1>Home</h1>} />
    <Route path="*" element={<PageNotFound />} />
  </Routes>
</BrowserRouter>

The webpack.config.js for the NPM package includes rules that use ts-loader, style-loader, css-loader, and sass-loader. Do I need another loader for png/jpg images to load from the NPM package correctly?

CodePudding user response:

I ended up using Webpack 5's asset/inline module to inline these images into the SCSS file, I'm not sure if this is the "ideal" way but it worked for my use case.

{
  test: /\.(png|jpe?g|gif)$/i,
  type: 'asset/inline'
}
  • Related