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!
In webpack 4, the bundle-level minification is enabled automatically – both in the production mode and without one. It uses the UglifyJS minifier under the hood. (If you ever need to disable minification, just use the development mode or pass false to the optimization. minimize option.)
webpack uses loaders to preprocess files loaded via modules. This can be JavaScript files, static assets like images and CSS styles, and compilers like TypeScript and Babel. webpack 5 has a few built-in loaders for assets as well.
This can be JavaScript files, static assets like images and CSS styles, and compilers like TypeScript and Babel. webpack 5 has a few built-in loaders for assets as well. In your project you have an HTML file that loads and brings in some JavaScript, but it still doesn't actually do anything.
In this article, I want to tell you about the Asset Modules - an experimental feature of webpack 5, which makes it possible to throw out a few habitual loaders, but not to cut these functionalities. Let's imagine that we need to bundle a page with some images and styles. import './styles.css'; // ...
DevServer | webpack webpack is a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset. webpack is a module bundler.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With