I have a simple library that export an <Image name="cat" /> component. The component will use the name prop to figure out the correct src value for the underlining <img /> tag.
However, I'm having trouble when bundling it with webpack (or maybe the problem itself is that I am trying to bundle it before publishing to npm). Here's some code to better paint a picture:
import cat from "../images/cat.png"
import dog from "../images/dog.png"
const images = { cat, dog }
const Image = ({ name }) => (
<img src={images[name]} />
)
{
test: /\.(png|jpg|gif|svg)$/,
use: [{
loader: 'file-loader',
options: {
name: '[path][name].[ext]'
}
}]
},
After I have run webpack on my library, the dist/ directory will contain a directory with both dog.png and cat.png. The transpiled minified code will have string references to them. So I publish it to npm.
Now, here's the part that gets me. When I install the published package on my project and run it, and I consume the <Image name="dog" /> component, the rendered img will still have the correct path (/images/dog.png), but webpack-dev-server hasn't realised it needs to process said file into the public directory. So in the browser, the URL resolves not on the image, but on the index.html.
Now, if instead I import the image directly to my project like import dog from "my-library/images/dog.png, then webpack correctly processes it.
I can think of a few things I'm doing wrong, but ultimately need some guidance:
Image component would never work.How should I proceed?