Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use webpack with static image files?

I am using webpack to bundle .vue files, which use import and export. Webpack creates a nice bundle.js and that's all fine and dandy.

BUT when my Vue file mentions an image, for example:

<div>
     <img src='./images/thing.png'>
</div>

.style {
   background: url('./images/anotherthing.png');
}

Now, suddenly this image needs to be in my dev folder as well, and webpack wants to copy ALL my image files each and every time I update one character in one javascript file. Also, not ALL my images are imported this way, so I have to copy some files manually to the dist folder, and webpack also copies some files...

Can I tell webpack not to bundle static image files that never change? Is that even recommended?

like image 406
Kokodoko Avatar asked Jan 12 '18 20:01

Kokodoko


3 Answers

Webpack has a file-loader which will handle copying static dependencies and resolving their URLs correctly:

https://webpack.js.org/loaders/file-loader/

Here is more in depth discussion about images specifically: https://webpack.js.org/guides/asset-management/#loading-images

like image 168
VivaLaPanda Avatar answered Nov 12 '22 02:11

VivaLaPanda


Let's say we have following structure: - public/ - dist/ - static/ - src/ - webpack.config.js You can keep your static images in static directory and all files built by webpack in dist directory. Set webpack directory to src. Webpack will work with only src directory and your static files will be separated from webpack.

And use webpack watch: true. Webpack will compile only changed code not all project.

like image 32
Martin Avatar answered Nov 12 '22 02:11

Martin


You can use a different file extension to handle certain images differently. Be sure to include the ignore-loader before the file-loader:

{ test: /ignore\.(png|jpg|gif|svg)$/, loader: 'ignore-loader' },
{ test: /\.(png|jpg|gif|svg)$/, loader: 'file-loader', options: { name: '[name].[ext]?[hash]' } }

Then include your image using the prefixed extension:

<img src='./images/thing.ignore.png'>

You'll need to rename the file to thing.ignore.png as well.

like image 1
sidhuko Avatar answered Nov 12 '22 01:11

sidhuko