Quick tip when using webpack and npm packages that use relative url paths

I wanted to share a solution to what I think is a very common issue people run into when they are new to webpack.

When I started to use webpack I kept running into issues when I wanted to use npm libraries. The issue was when I required a css file from the package it usually had a background image or some other url() path that was relative to the css file.

What I learned was that if that file that was trying to load was an image of some form, I first needed to make sure I had a loader for that. In the case of this being an image you would use the file loader. This meant I need to have something like so in my webpack config’s rules.

  test: /\.(png|svg|jpg|gif)$/,
  use: [
      loader: "file-loader",
      options: {
        outputPath: "../images/"

the outputPath option for the file loader allowed me to state where I would like to have webpack place the images that it found while it loaded the css.

This is how you will commonly address any of the “Not found” type errors while your webpack compiles as it relates to css urls.

Be aware that the outputPath is relative to the css file, for me in this case that is my css folder, thus I jump up one directory and then in to my images via "../images/"

Read more on this option here https://github.com/webpack-contrib/file-loader#outputpath

Note: This post assumes you are at least familiar with webpack rules to some level. If not I’d recommend you read webpack’s docs

Happy coding!