How to Use Images in CSS with Webpack

How to use images in css with Webpack

I was stuck with similar issue and found that you can use url-loader to resolve "url()" statements in your CSS as any other require or import statements.

To install it:

npm install url-loader --save-dev

It will install the loader that can convert resolved paths as BASE64 strings.

In your webpack config file use url-loader in loaders

{
test: /\.(png|jpg)$/,
loader: 'url-loader'
}

Also make sure that you are specifying your public path correctly and path of images you are trying to load.

Resolving css background-image url with Webpack

You are may be using a new version of Webpack, where url-loader and file-loader are deprecated and Asset Modules are the alternatives.

Try using:

{
test: /\.(jpg|png|svg|gif)$/,
type: 'asset/resource',
},

instead.

For more information click here.

webpack file-loader does not load background image

Adding esModule: false inside the url-loader options the image helped me, though I'm not sure why, if someone has the same issue you should try this trick.

Webpack & SCSS: how to work with image paths?

Problem solved by adding publicPath: '../' (docs) and useRelativePaths: true (docs):

module.exports = {
// ...
module: {
rules: [
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
context: path.resolve(__dirname, "src/"),
outputPath: 'dist/',
publicPath: '../',
useRelativePaths: true
}
}
]
}
]
},
plugins: [
new ExtractTextPlugin({
filename: 'dist/[name].bundle.css',
allChunks: true
})
]
};

Webpack 5 How to display images in HTML file

You need to change your legacy assets loaders... For images, it's recommended to use asset/resource.

Use asset/resource instead file-loader.
something like:

edit your rule:

{
test: /\.(png|jpg|gif|svg|eot|ttf|woff)$/,
type: 'asset/resource'
}

and add in your webpack.output this:

output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
assetModuleFilename: 'src/assets/images/[name].[ext]'
}

You can see more details on Webpack assets loader guide

Webpack, CSS: where to put images?

as much i understand you don't need to do any thing, webpack will take care of it for you. Let say you have a folder call images some where and you want this

.mydiv {
background: url("/public/images/test.png");
}

webpack will bundle this in dist folder you, it will also change it name with something else and even path in url. in my case i had url like this

background: url("../../assets/webpack+angular.png")

and when i run webpack i got a file called dist/f1305c1f7292179760078b1efdee3ffa.png
and my url look like this

url(/f1305c1f7292179760078b1efdee3ffa.png);

and everything works just fine. You don't need to use require in css.



Related Topics



Leave a reply



Submit