Making webpack 5 asset loader work with webpack-dev-server

Viewed 552

My project structure is

├──images  
|  └─cat.jpg
├──components
|  └─App.jsx
├──webpack.prod.js
├──webpack.dev.js

In webpack.dev, dev-server settings I have contentBase: path.resolve(__dirname, 'images')

and in webpack.prod:

rules: {  
           test: /\.jpg/,  
           type: 'asset/resource',  
       },  

now if I try to display my image in App.jsx as <img src='cat.jpg'/>, then it works in dev but not in prod which 404s. That makes sense, because I'm not importing the image and webpack doesn't "see" it in the bundle, and contentBase is dev only.

I've also tried

import cat from '../images/cat.jpg';
...
      <img src={cat}></img>

but this works in prod, but crashes in dev, which also makes sense because there's no asset loader in dev. I can add the loader in dev too, but I feel like that defeats the purpose of having contentBase settings, which can then be removed entirely.

So my question is: is it possible to use contentBase in dev to display the image, and use the asset loader only in prod? Feels like it should somehow...

Thanks!

2 Answers

I am not using contentBase at devServer on my webpack. But it's working on both dev and prod with the following:

Structure

├──images  
|  └─logo.png
├──components
|  └─App.jsx

Webpack

...
output: {
  ...
  assetModuleFilename: 'images/[hash][ext][query]'
},
module: {
  rules: {
    test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
    type: 'asset/resource'
  },
...

App.jsx

import Logo from '../images/logo.png'

<img src={Logo}></img>

I also got this issue when using webpack 5 in electron, assetModuleFilename: 'images/[hash][ext][query]' does't exactly work for me. try to turn import demo from './assets/demo.png' to import * as demo from './assets.png'. it finally worked

Related