Exploring methods for handling svgs incorporated in angular.js templates with webpack

I'm currently working on cache-busting my SVGs and other files like translation JSON.

The issue I'm facing is that webpack does not seem to recognize imported svgs in the following format:

<md-icon md-svg-src="assets/icons/ic-edit.svg"></md-icon>

I am looking for a way to hash the file names so using CopyWebpackPlugin to copy and hash assets won't work, as it would require manual updates within the markup.

{
   test: /\.svg$/,
   loader: 'file-loader',
   options: {
     name(file) {
        // The console doesn't log anything as it's not detecting urls within Angular templates
        console.log(file); 
        return '[name]-[hash].[ext]'
    }
  }
}

What are my options for handling SVG files within my application? It seems like a significant task to refactor all of the SVGs from template usage to importing them in JavaScript and utilizing them inline. Is there another solution available or is this the best approach?

Answer №1

After some trial and error, I successfully configured webpack to process svgs. It was a bit of a journey getting there, especially since this is based on webpack2 and adaptations may be needed for different webpack versions.

  1. To make angular work with svg icons, I had to define custom src attributes
  2. I had to specify when the HTML should start parsing absolute paths using root
  3. I included a name property for assets and utilized file loader for this purpose

I also had to adjust my asset paths from:

"assets/icons/ic-edit.svg"

"/assets/icons/ic-edit.svg"

{
  module: {
    loaders: [
      {
        test: /\.html$/,
        loaders: 'html-loader',
        options: {
          attrs: ['md-icon:md-svg-src', ':ng-src'],
          root: path.resolve(__dirname, '../src'),
          name: '[name]-[hash].[ext]'
        }
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: '[name]-[hash].[ext]'
        }
      }   
    ],
  }
}

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

Is there a method in JavaScript to access the object to which a function was originally bound?

I have a curiosity about making the code below function properly, capturing the logging as instructed in the comments. function somePeculiar(func) { var funcThis = undefined; // Instead of undefined, how can we access // ...

How to confirm the parent state in Angular's UI router?

In summary, I am seeking a function similar to state.is() that can verify a state with multiple child states from one of those child states? This is the structure I have: Parent 1 Child 1.1 Child 1.2 Child 1.3 Parent 2 Child 2.1 ...

What is the method for retrieving an attribute's value from an object that does not have key-value pairs?

My current project involves working with dynamoose and running a query that produces the following output: [ Document { cost: 100 }, lastKey: undefined, count: 1, queriedCount: undefined, timesQueried: 1 ] When I use typeof(output), it returns O ...

Incorporating a Favicon into your NextJs App routing system

Encountering an issue with the new Next.js App Router. The head.js files have been removed, thus according to the documentation I need to implement metadata in layout.ts. My favicon file is named favicon.png. How should I specify it within the following c ...

Update Jquery Dialog's Button After Making an Ajax Request

I am facing an issue with my dialog window that contains some confirmation elements following a form submission: $('#newUserDialog').dialog({ autoOpen: false, width: 600, modal: true, resizable: false, cl ...

Preventing background style from taking precedence over backgroundColor style in React's inline styling

What causes background to take precedence over backgroundColor in React inline-style? In this scenario, the lack of a specified green background-color results in the background gradient with transparency transitioning into white rather than green within t ...

Acquire by Identifier - Tonic()

Currently, I am in the process of setting up a code example on tonicdev.com for my open-source React component available on Npm. Below is the code snippet that I am attempting to execute (editable live on tonicdev.com here): var React = require('rea ...

What is the process for creating a personalized module in AngularJS?

Looking to create a bespoke module for AngularJS, but struggling to locate comprehensive documentation. What is the best approach to develop a custom AngularJS module that can be easily shared with others? ...

Unable to decipher the mysterious map of nothingness

I am currently working on a GET method in Node.js. My goal is to fetch data using the GET request and then use the MAP function to gather all the names into an array. However, I encountered the following error: /root/server.js:21 ...

A guide on how to initiate a click event in Angular 5 using JQuery

I am trying to trigger a click event for each element based on its id, but it doesn't seem to be working. Below is the code I am using: ngOnInit() { this.getProductsLists(); } getProductsLists() { this.supplierService.getProductLists() .sub ...

Methods for conducting trials on a module's block

Seeking guidance on how to test the code in a run block of my AngularJS app. The code is responsible for making an http request to fetch user information from the server or redirecting to the login screen. Should I keep this initialization code in the run ...

Using pre-built modules in an environment that does not support Node.js

Despite the limitations on node API usage (such as fs, http, net...), vanilla JS can still be used on any engine. While simple functionalities can be easily extracted from packaged modules if licensing terms are met, things get complicated when dealing wit ...

Issue with jQuery hide() function in Internet Explorer 9

I need help with creating a hidden div that becomes visible when a user clicks a link. The code I have works in FF / IE7 / IE8 but not in IE9, where the div is always visible without any content. Any advice is appreciated! <script> $(document).r ...

Can ajax requests be made without a web browser?

Currently, I am in the process of developing JavaScript tests using mocha and chutzpah, which means conducting all my tests without a browser. However, I have encountered an issue where all my AJAX calls are resulting in empty strings. Even when using the ...

Passing along the mouse event to the containing canvas element that utilizes chart.js

Recently, I created a custom tooltip for my chart.js chart by implementing a div that moves above the chart. While it works well, I noticed that the tooltip is capturing mouse events rather than propagating them to the parent element (the chart) for updati ...

What are the best practices for establishing a secure SignalR client connection?

While tackling this issue may not be solely related to SignalR, it's more about approaching it in the most efficient way. In C#, creating a singleton of a shared object is achievable by making it static and utilizing a lock to prevent multiple threads ...

Use the knockout textInput plugin in combination with the maskedinput plugin

Is there a simple way to use data-bind="textInput: aProperty" and apply an input mask or automatic formatting while the user is typing? Although using the masked input plugin somewhat works, it results in losing the real-time updates that Knockout's ...

What is the best way to remove a property from an object in React if the key's value is set to false?

I'm currently working on a form component and I've encountered an issue. Whenever I submit the form, it returns an object with various fields such as email, fieldName1, fieldName2, first_name, last_name, and organization. Some of these fields are ...

Updating NavBar text dynamically based on user login status in React.JS

Within my project, there is a Navigation bar that I access from App.js. Depending on whether I am logged in or not, I want to display different versions of the NavBar. When logged in, the NavBar should have a logout button. And when logged out, it should s ...

What is the process for rendering a React class component using React HashRouter and Apollo client?

I've run into an issue with my project that involves using only React class components and fetching data from an Apollo server. The problem I'm facing is that, in Chrome, only the Navbar.jsx component is rendering. Even when I navigate to one o ...