Lately, I encountered this issue and discovered that the information on StackOverflow was outdated. This is not surprising considering how rapidly things evolve in the realm of NPM & Web Development.
The good news is that Webpack 5 has resolved this problem straight out of the box. All you need to do is update the webpack.config.js
file.
You can find more details about this in webpack's documentation here: https://webpack.js.org/guides/asset-modules/
The solution involves Base64 encoding your static assets and inlining them into your CSS/JavaScript files.
When preparing your source code for distribution on NPM, if your CSS file references static images like this:
background-image: url(./image.png)
, you should inline your assets into your style file and then process it using the
style-loader
and
css-loader
packages.
In my case, adding the following lines to my webpack.config.js
solved the issue and enabled me to export a single index.js
file along with my package, which I could import into other projects:
The crucial line to pay attention to here is type: asset/inline
when dealing with images.
webpack.config.js
...
...
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ["babel-loader"],
},
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
{
test: /\.(png|jpg|gif)$/i,
type: "asset/inline",
},
],
},
...
...