I am currently facing an issue with Vue Cli 3 where I am unable to process SVG files using Webpack

By default, Vue Cli uses file-loader for SVG assets. However, I want to use svg-sprite-loader and a few other loaders instead.

I have made changes to the vue.config.js file in order to achieve this, but it seems like the configuration is not being applied at all.

vue.config.js

module.exports = {
  configureWebpack: {
    module: {
      rules: [
        {
          test: /\.(svg)(\?.*)?$/,
          use: [
            {
              loader: 'svg-sprite-loader',
              options: {
                name: '[name]-[hash:7]',
                prefixize: true
              }
            },
            'svg-fill-loader',
            'svgo-loader'
          ]
        }
      ]
    }
  }
}

Can anyone spot any issues with my setup?

I am still experiencing the problem where SVG files are being imported into my component as URL strings or paths rather than objects with properties.

Thank you in advance!

Answer №1

After spending some time working on it, I finally found a solution. In order to prevent file-loader from matching .svg files, I used chainWebpack and returned false from the test method on file-loader. Below is my updated configuration:

module.exports = {
  lintOnSave: false,
  configureWebpack: {
    module: {
      rules: [
        {
          test: /\.(svg)(\?.*)?$/,
          use: [
            {
              loader: 'svg-inline-loader',
              options: {
                limit: 10000,
                name: 'assets/img/[name].[hash:7].[ext]'
              }
            }
          ]
        }
      ]
    }
  },
  chainWebpack: config => {
    config.module
      .rule('svg')
      .test(() => false)
      .use('file-loader')
  }
}

Answer №2

The latest update to the Vue CLI 3.0 beta documentation in Webpack now includes an illustration of how to swap out an existing Base Loader. To replace the svg-sprite-loader, you will need to insert the following configuration into your vue.config.js:

chainWebpack: config => {
  config.module
    .rule('svg')
    .use('file-loader')
    .loader('svg-sprite-loader')
}

Answer №3

I am currently utilizing Vue CLI version 3.0.3 and have found this configuration to be successful 😊

const path = require('path');
const glob = require('glob');
const SpriteLoaderPlugin = require('svg-sprite-loader/plugin');

module.exports = {
  lintOnSave: false,
  configureWebpack: {
    plugins: [
      new SpriteLoaderPlugin()
    ]
  },
  chainWebpack: config => {
    config.module.rules.delete('svg');

    config
      .entry('app')
      .clear()
      .add(path.resolve(__dirname, './src/main.ts'))

    config
      .entry('sprite')
      .add(...glob.sync(path.resolve(__dirname, `./src/assets/icons/*.svg`)));

    config.module.rule('svg')
      .test(/\.(svg)(\?.*)?$/)
      .use('file-loader')
      .loader('svg-sprite-loader')
      .options({
        extract: true,
        spriteFilename: 'icons.svg'
      })
  }
};

Answer №4

According to the Vue CLI documentation for version 3.x, the webpack section recommends using the following code snippet:

// vue.config.js
module.exports = {
  chainWebpack: config => {
    const svgRule = config.module.rule('svg')

    // clear all existing loaders.
    // if you don't do this, the loader below will be appended to
    // existing loaders of the rule.
    svgRule.uses.clear()

    // add replacement loader(s)
    svgRule
      .use('vue-svg-loader')
      .loader('vue-svg-loader')
  }
}

Even the configuration guide for vue-svg-loader on NPM suggests the same approach.

Answer №5

export default {
  configureWebpack: config => {
    const svgLoader = config.module.rule('svg')

    svgLoader.clear()

    svgLoader
      .use('vue-svg-loader')
      .loader('vue-svg-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

Can I stream a file from an external server in NodeJS without routing it through my own server?

My website provides links for downloading or streaming media files from another server. Currently, my setup looks something like this: download = (req, res) -> song_id = req.params.id download_url = "http://mediaserver.com/#{song_id}" console.log ...

Can you explain the purpose of the .subscribe() function?

Currently, I am in the process of developing an API using Angular2 and NodeJS. My focus has been on implementing services for my API that are responsible for retrieving a list of tasks and presenting them. Below is the code snippet for the task service: i ...

Issue with react-router-dom: <Route> elements are strictly meant for configuring the router and should not be rendered on their own

I've been grappling with this issue for quite some time now, but none of my attempts have succeeded and I keep encountering the same error: < Route> elements are for router configuration only and should not be rendered Here's the snippet ...

Using ES6 to generate objects within other objects

Dealing with data from a local API can be challenging, especially when you have limited control over the incoming data. However, I am looking to transform the data post my API call using a custom function. This is my current approach transformArray = () ...

Strategies for maintaining pristine Firebase child paths

I have a list of data that I want to structure in Firebase. However, I encountered an error: Error: Firebase.child failed: The first argument provided is not a valid path. Path names should not include ".", "#", "$", "[", or "]" characters and must be no ...

The Jest snapshot test fails to capture any styling applied to children components

Struggling with creating a snapshot test for a straightforward react-native component. Jest's snapshot lacks necessary styling and content details for the single child of the component. The component is a basic button from native-base with an icon em ...

Nuxt Axios not connecting with proxy leading to CORS issues

Encountering the following CORS error: Access to XMLHttpRequest at 'https://gw.bilinfo.net/listingapi/api/export' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass acce ...

Navigating through web pages and creating dynamic interfaces is made simple

As someone relatively new to React, I am currently exploring how to integrate React Router with Material UI. In my Layout file, I have implemented a Navigation drawer from Material UI with the menu on the left and content on the right, as depicted in the ...

What is the best way to incorporate async/await in a useEffect hook in a React Native application?

Upon executing useEffect, my objective is to retrieve the token from AsyncStorage, fetch the data value using the axios.post('/auth/me') endpoint, and trigger the KAKAOLOG_IN_REQUEST action through dispatch. After verifying that the data value i ...

The correlation between the input field and the graphic

Hello, I have a question for all you ASP.NET professionals out there: I am working on a project where I have multiple dynamically generated textboxes in a row. Within the same row, there is also an image that has an onclick event handler. My goal is to e ...

Leveraging the power of Firebase and JavaScript to easily include custom user fields during the user

UPDATE: I encountered an issue while using Nextjs framework. However, it works perfectly fine when I use a vanilla CRA (Create React App). It appears that the problem is somehow related to Nextjs. I'm currently working on creating a new user document ...

Encountering difficulties while attempting to convert JSON to XML resulting in an error being

I can't seem to figure out how to successfully convert the JSON result into XML format. I've tried the code below but it's not working as expected. Any help would be greatly appreciated. Here is the code snippet: <script src="../Jquery ...

Eliminate the navigation bar option from a website template

Is there a way to permanently eliminate the menu button in this theme? Any guidance would be appreciated. Here's the link to the theme: https://github.com/vvalchev/creative-theme-jekyll-new ...

The npm install command failed due to a lack of suitable versions for pinkie-promise

I am currently attempting to perform a straightforward "npm install" from one of the repositories mentioned in a tutorial provided here Below is the content of the package.json: { "name": "react-playlist", "version": "1.0.0", "description": "A basi ...

Tips for formatting the output of data returned by axios to meet specific requirements

<template> <div> <table class="table table-responsive"> <tbody> <tr v-for="(gameresult, index) in gameresults" :key="index"> <td style=&q ...

Frontend experiencing issues with Laravel Echo Listener functionality

I have recently developed a new event: <?php namespace App\Events; use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\PresenceChannel; use Illuminate&bs ...

Is there a way to turn off data sorting on the x-axis of a d3 line chart?

I am looking to create a line graph similar to the example shown here. My JSON data is structured as follows: [ { "timeStamp": "23:33:58", "usage": 90 }, { "timeStamp": "00:04:03", "usage": 94 }, { ...

How can I securely store passwords for web scraping with Puppeteer to ensure maximum safety?

Looking for advice on scraping a website that requires login. The current code saves username and password in a config JSON file, which poses a security risk if the file is accessed by unauthorized individuals. Is there a more secure method, such as encr ...

A tutorial on how to switch out a font-awesome icon simply by clicking on it - collapsible content

I have some HTML code with a script for my website that allows text to be collapsed or expanded by clicking on a font awesome arrow. I am looking to have an arrow that points up when clicked to collapse the text and points down when clicked to expand the t ...

JavaScript displays an invalid dateerror message

When I create a date like this, everything works fine: var someDate = new Date("2013,2,1");. However, I want to include time with this date as well. The following suggestion on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objec ...