Minifying images is not performed in the Vue Webpack configuration

Currently, I am developing a straightforward card game that features about 40 images corresponding to different cards. My project utilizes Vue Cli, which comes equipped with a basic webpack setup.

Essentially, all images are stored in the static folder like this:

https://i.sstatic.net/YEGup.png

Once I compile the project for production and generate the dist folder, it presents the images in this format:

https://i.sstatic.net/IUVIx.png

This is my current webpack configuration for production:

'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

const env = process.env.NODE_ENV === 'testing'
  ? require('../config/test.env')
  : require('../config/prod.env')

const webpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true,
      usePostCSS: true
    })
  },
  devtool: config.build.productionSourceMap ? config.build.devtool : false,
  output: {
    path: config.build.assetsRoot,
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },

<!-- More webpack config settings -->

    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

if (config.build.productionGzip) {
  const CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

if (config.build.bundleAnalyzerReport) {
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig

If anyone can provide assistance or insights regarding this setup, it would be greatly appreciated. Thank you!

Answer №1

It seems like you may have utilized vuejs-templates/webpack, which does not come with built-in image optimization. To incorporate this feature, you can easily do so by adding imagemin-webpack-plugin to your Webpack configuration:

  1. Begin by installing ImageminWebpackPlugin using: npm i -D imagemin-webpack-plugin
  2. In build/webpack.prod.conf.js, import the plugin and set it up within plugins[] (following CopyWebpackPlugin):

    const ImageminPlugin = require('imagemin-webpack-plugin').default;
    
    const webpackConfig = merge(baseWebpackConfig, {
      plugins: [
        // ...
        new ImageminPlugin({
          test: /\.(jpe?g|png|gif|svg)$/i,
          /* other ImageMin configurations */
        })
      ]
    }
    

By running ImageminWebpackPlugin after CopyWebpackPlugin, you ensure that images copied from static undergo ImageMin optimization.

Check out the GitHub repository demo

Answer №2

If you are working with the latest version of Vue, you have the option to utilize a vue.config.js file that is structured like this:

const ImageminPlugin = require('imagemin-webpack-plugin').default;

module.exports = {
  configureWebpack: {
    plugins: [
      new ImageminPlugin({
        disable: process.env.NODE_ENV !== 'production',
      })
    ]
  }
}

By implementing this configuration, Imagemin will be activated during production builds while being omitted during development builds.

Answer №3

Why not give it a shot? This tool simplifies the process of optimizing images without the need for complex algorithm configurations. It also offers the convenience of encoding (and inline) images, providing more flexibility compared to traditional url-loader.

Check it out on GitHub

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|webp|gif|svg|)$/i,
        use: [
          {
            loader: 'img-optimize-loader'
          },
        ],
      },
    ],
  },
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

how to toggle visibility of bootstrap accordion panel using jQuery

I have a bootstrap accordion that I want to customize. Specifically, I only want to enable a panel under specific conditions. The idea is for the second panel to be collapsible only when the first panel is valid. <div class="panel-group" id="accordion" ...

Is there a way to retrieve the groups of match/matchAll similar to accessing an array?

My goal is to convert a version string to a number using the following code: function convertVersionToNumber(line) { const groups = line.matchAll(/^# ([0-9]).([0-9][0-9]).([0-9][0-9])\s*/g); return parseInt(groups[1] + groups[2] + groups[3]) ...

Utilize Node.js and Socket.IO to download a PNG image in a web browser

Looking for assistance in saving an image from Flash to a server using node.js. Below is my code snippet: var pngEncoder:PNGEncoder = new PNGEncoder(); var pngStream:ByteArray = PNGEncoder.encode(bmd); socket.send(pngStream,"image"); Above is the Flash c ...

Is there a way to determine if a certain class link within a DIV has been clicked and then replace the DIV's click functionality?

I have multiple DIV elements like the one below on my webpage: <div class='entry'> This is a statement <a title="Search @travel" class="app-context-link" href="">@travel</a> </div> When a DIV with the class .ent ...

In React-router-dom version 5, match.params.id functions properly, but it experiences issues in version 6

Can anyone help me figure out the proper way to achieve this functionality in react-router version 6? When I use console.log with match, it returns undefined, even though it works fine in v5. import React from 'react' const NotePage = ({ match } ...

What is the best way to troubleshoot a $http asynchronous request?

Is there a way to pause the program execution in AngularJS $http call after receiving a successful response? I've attempted to set a breakpoint at that point, but it does not halt the execution. I've also tried using the debugger directive, but ...

tag of data in jquery

Here is how my setup looks: <div onclick="EditCalendarEvent('@_schedulerEvent.SchedulerID','@_schedulerEvent.SchedulerItemID', event)" class="ScheduleEvent_Draggable ScheduleEvent" data-schedulerID="@_schedul ...

Managing multiple layouts in Nuxt.js when dealing with child pages - a comprehensive guide

Exploring the world of Nuxt.js and Vue.js for the first time has been an exciting journey. I am currently working on creating a template where I need to have two columns, with each column displaying different data. layouts/content.vue: <template> ...

Node.JS: Combining Multiple Files into a Single Output File

Currently, I am in the process of building a data pipeline using Node.js. While I acknowledge that there are better ways to approach this, I am determined to implement it and make improvements as I go. Here's the scenario: I have a collection of gzi ...

What is the most effective method for live-updating a field every 5 seconds in Laravel?

I want to monitor the database to see if a new row is created for each user and display a popup message to notify them. I'm debating between using pusher/socket or making an Ajax call every 5 seconds to achieve this live update without page refresh. I ...

Typescript struggling to load the hefty json file

Currently, I am attempting to load a JSON file within my program. Here's the code snippet that I have used: seed.d.ts: declare module "*.json" { const value: any; export default value; } dataset.ts: import * as data from "./my.json" ...

Issue with loading HTML file correctly in Django

I have been attempting to integrate my Django app with an admin dashboard from a repository on GitHub. After successfully logging in, the app redirects to the dashboard, but only the HTML part loads and none of the fancy features are visible on the dashboa ...

Adjust the appearance of an element based on user selection from a dropdown menu under certain circumstances

I am working on creating a dropdown menu using a JavaScript array. My goal is to display a specific span element when certain options are selected. For instance, I want the span to be shown only when options "a" and "c" are selected, but not when option " ...

Retrieve information from a child component in Vue and link it to an object in the parent component

<user-data @change="setUserInfo"></user-data"> this particular component serves as the child element where data is passed using emits. Below is the snippet of code from the parent component. setUserInfo(data) { this.obj.paym ...

Problem with Angular2, NodeJS, and Passport Integration

At the moment, my Angular2 front-end is running on localhost:3000 while the NodeJS back-end (using KrakenJS) is running on localhost:8000. When I input the credentials and make a call to the this.http.post('http://localhost:8000/login', body, { h ...

Angular 8 is throwing a NullInjectorError because it cannot find a provider for AngularFireAnalytics

After running 'npm test', I encountered the following error message: NullInjectorError: StaticInjectorError(DynamicTestModule)[ComparePageComponent -> AngularFireAnalytics]: StaticInjectorError(Platform: core)[ComparePageComponent - ...

Incorporating grids for a flickering drag and drop effect in Javascript

I have been working on developing a selection system for a tilemap image where users can select multiple tiles by dragging the mouse to increase the size of the selection container. However, I've noticed a flickering effect while holding down the mous ...

Using Jquery for a synchronous "Ajax" request doesn't seem to be functioning

As a newcomer to javascript, I am currently in the process of developing a react/flux app and utilizing jquery for synchronous "ajax" calls (sjax?) to the backend. However, I am encountering inconsistent behavior which seems to be caused by my ajax call no ...

Tips on verifying the count with sequelize and generating a Boolean outcome if the count is greater than zero

I'm currently working with Nodejs and I have a query that retrieves a count. I need to check if the count > 0 in order to return true, otherwise false. However, I am facing difficulties handling this in Nodejs. Below is the code snippet I am strugg ...

What are some ways to troubleshoot the UI of a Nativescript app?

As a newcomer to NativeScript technology, I often encounter challenges while developing applications. Whether it's troubleshooting why a textview is not displaying properly, identifying layout overlaps, or detecting other distortions in the UI, debugg ...