webpack is failing to load SVG files

My application structure includes:

/webapp
  /lib
    /assets
      ic_add_black_24px.svg
      ic_clear_black_24px.svg
      ..
      ..

The configuration in my webpack.config.js looks like this:

var path = require('path'),
    webpack = require("webpack"),
    libPath = path.join(__dirname, 'lib'),
    wwwPath = path.join(__dirname, 'www'),
    pkg = require(path.join(__dirname,'package.json')),
    HtmlWebpackPlugin = require('html-webpack-plugin');


var config = {
    entry: path.join(libPath, 'index.js'),
    output: {
        path: path.join(wwwPath),
        filename: 'bundle-[hash:6].js'
    },
    module: {
        loaders: [{
            test: /\.html$/,
            loader: 'file?name=templates/[name]-[hash:6].html'
        }, {
            test: /\.(png|jpg|svg)$/,
            loader: 'file-loader?name=assets/[name].[ext]'
        }, {
            test: /\.css$/,
            loader: "style!css"
        }, {
            test: /\.scss$/,
            loader: "style!css!autoprefixer!sass"
        }, {
            test: /\.js$/,
            exclude: /(node_modules)/,
            loader: "ng-annotate?add=true!babel"
        }, {
            test: [/fontawesome-webfont\.svg/, /fontawesome-webfont\.eot/, /fontawesome-webfont\.ttf/, /fontawesome-webfont\.woff/, /fontawesome-webfont\.woff2/],
            loader: 'file?name=fonts/[name].[ext]'
        }]
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename: 'index.html',
            pkg: pkg,
            template: path.join(libPath, 'index.html')
        }),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.DedupePlugin()
    ]
};

module.exports = config;

To include an SVG asset in my HTML file, I use the following code snippet:

<md-card-header>
            <span flex></span>
            <md-button class="md-icon-button" aria-label="remove condition" style="background-color: #DCD8D8" ng-click="event.removeCondition(condition)">
                <md-icon md-svg-src="/lib/assets/ic_clear_black_24px.svg"></md-icon>
            </md-button>
        </md-card-header>

However, after running

rm -rf www/* && webpack -p
, the bundle is created successfully but without loading any assets. I have tried using svg-loader, url-loader, file, but none of them seem to work. Can you help me figure out what might be wrong here?

Answer №1

If anyone is looking for a solution, I found that using CopyWebpackPlugin helped me to manually load assets to the desired location. Here's how my updated webpack.config file looks:

var path = require('path'),
    webpack = require("webpack"),
    libPath = path.join(__dirname, 'lib'),
    wwwPath = path.join(__dirname, 'www'),
    pkg = require(path.join(__dirname,'package.json')),
    CopyWebpackPlugin = require('copy-webpack-plugin'),
    HtmlWebpackPlugin = require('html-webpack-plugin');


var config = {
    entry: path.join(libPath, 'index.js'),
    output: {
        path: path.join(wwwPath),
        filename: 'bundle-[hash:6].js'
    },
    module: {
        loaders: [{
            test: /\.html$/,
            loader: 'file?name=templates/[name]-[hash:6].html'
        }, {
            test: /\.(png|jpg|svg)$/,
            loader: 'svg-url-loader?name=assets/[name].[ext]' // inline base64 URLs for <=10kb images, direct URLs for the rest
        }, {
            test: /\.css$/,
            loader: "style!css"
        }, {
            test: /\.scss$/,
            loader: "style!css!autoprefixer!sass"
        }, {
            test: /\.js$/,
            exclude: /(node_modules)/,
            loader: "ng-annotate?add=true!babel"
        }, {
            test: [/fontawesome-webfont\.svg/, /fontawesome-webfont\.eot/, /fontawesome-webfont\.ttf/, /fontawesome-webfont\.woff/, /fontawesome-webfont\.woff2/],
            loader: 'file?name=fonts/[name].[ext]'
        }]
    },
    plugins: [
        new CopyWebpackPlugin([{
                from: 'lib/assets',
                to: wwwPath + '/lib/assets'
            }]),
        // HtmlWebpackPlugin: Simplifies creation of HTML files to serve your webpack bundles : https://www.npmjs.com/package/html-webpack-plugin
        new HtmlWebpackPlugin({
            filename: 'index.html',
            pkg: pkg,
            template: path.join(libPath, 'index.html')
        }),

        // OccurenceOrderPlugin: Assign the module and chunk ids by occurrence count. : https://webpack.github.io/docs/list-of-plugins.html#occurenceorderplugin
        new webpack.optimize.OccurenceOrderPlugin(),

        // Deduplication: find duplicate dependencies & prevents duplicate inclusion : https://github.com/webpack/docs/wiki/optimization#deduplication
        new webpack.optimize.DedupePlugin()
    ]
};

module.exports = config;

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

Setting a single value for several identifiers within a JSON object

I'm new to JSON and I'm curious if it's possible to have a name/value pair with multiple names. Essentially, I want to be able to search for either name and retrieve the same value without having to update the value in two different places. ...

Generating a clickable link for a variable within javascript

$scope.msg = "Data Updated Successfully. Item ID: " + $scope.id; After successfully updating any data, a message will be displayed as "Data Updated Successfully. Item ID: 13456". I want to turn the ID into a clickable hyperlink. Here is what I have attem ...

using java to invoke a server-side function within a mapReduce operation in mongodb

i have saved two functions in the "system.js" collection under the names "mapfun" and "reducefun" and now i am attempting to invoke these functions from Java. I am trying to utilize MapReduceCommand for this purpose but encountering difficulties in calling ...

Initiating a Page with Dynamic Modal Window according to Backend Exigencies

Dear experts, can you help me with a problem? I want to implement a modal window on an vb.aspx page if a specific condition from the codebehind query is true. How can I achieve this? Thank you! ...

Displaying discard and save options only if the items do not match

Within the controller, I have this code that executes when the template is loaded: $scope.original_timesheet = angular.copy($scope.timesheet); Now, in the template, my goal is to achieve the following functionality: <div ng-show="(timesheet != origin ...

JQuery click event does not play nicely with Javascript array splice functionality

When using for loops, I noticed that array.splice doesn't seem to be working as expected. The array remains unchanged. I tried moving things around and found that it still doesn't work in Chrome. var menu =['#men','#wmen',&a ...

JavaScript / AngularJS - Efficient Boolean Switching

My group of Boolean variables can toggle other variables to false when set to true. I am looking for a clean pattern for this approach, especially since the number of boolean variables may increase. angular.module("app", []) .controller("controller", ...

Acquire user input using AngularJS

Is it possible to retrieve the value of an input text using AngularJS without utilizing a Controller? If so, what approach would achieve this? I have come across some resources discussing similar queries, but they all involve .controller here is one such ...

As the user types, the DD/MM/YYYY format will automatically be recognized in the

In my React component, I have an input box meant for entering a date of birth. The requirement is to automatically insert a / after each relevant section, like 30/03/2017 I am looking for something similar to this concept, but for date of birth instead of ...

How does the functionality of $.ajax differ from that of $.get?

Similar Inquiry: Understanding the Variations of $.ajax(), $.get(), and $.load() I'm curious about the disparities between $.get() and $.ajax The given code showcases calls like this: $.get(href) .success(function (content) { $(&apos ...

Error: The property 'postID' can not be read because it is undefined

I'm new to programming and I am working on creating a news/forum site as a practice project. I have set up a route /post/postID/postTitle to view individual posts. Initially, when I used only :postID, it worked fine. But after adding :postTitle, whene ...

Maintaining datatype integrity in MongoDB Stitch when decrementing with update statements

Using a MongoDB Stitch function, I have two collections: communities and posts. Whenever a new document is inserted in the post collection, I need to increment the summary.postCount in the communities collection by +1. Similarly, when the status of a post ...

CSS Class Not Updating in WordPress Using JavaScript

Looking to incorporate a small JavaScript code directly into The Twenty Sixteen theme in WordPress. This HTML Code needs to be modified on the Page: <p class="site-description">Example Text</p> The goal is to change a classname: document.g ...

Navigating in Angular with parameters without modifying the URL address

In a nutshell, my goal is to navigate to a page with parameters without showing them in the URL. I have two components: Component A and B. What I want to do is route to B while still needing some parameters from A. I know I can achieve this by setting a ...

Does invoking a regular function in $q behave synchronously or asynchronously?

* // In this scenario, suppose that variables `$q` and `okToGreet` are accessible in the existing lexical scope. They might have been delivered or passed as parameters. // Carry out an asynchronous task, resolving or rejecting the promise accord ...

Warning: The use of the outdated folder mapping "./" in the "exports" field for module resolution in the package located at node_modulespostcsspackage.json is deprecated

I recently upgraded my Node to version 16 and since then I have been encountering this issue while building my Angular app. Warning: The folder mapping "./" used in the "exports" field of the package located at ".../node_modules/postcss/package.json" is de ...

Styling elements using the nth-child selector in JavaScript

I am trying to apply a CSS class based on the combined height of the 2nd and 3rd child elements. For example, if the height of the 2nd child plus the height of the 3rd child equals a certain value, I want to add a specific class. Here is my JavaScript cod ...

Attempting to dynamically update the image source from an array when a click event occurs in a React component

Has anyone successfully implemented a function in react.js to change the image source based on the direction of an arrow click? For instance, I have an array set up where clicking the right arrow should move to the next image and clicking the left arrow s ...

What steps can be taken to ensure that the v-model input is not updated?

Typically, when a user enters a value in an input field, it automatically updates a model. However, I am looking to temporarily prevent this automatic update. In my application, I have a canvas where users can draw grids by entering lengths and widths in i ...

What is the process of changing a number to the double data type in JavaScript or TypeScript?

Within a single input field, users can enter various numbers such as 12, 12.1, 12.30, and 12.34. The challenge is to pass this value in a service call where only the value can be sent as a number but with two decimal points. let a = input //a will be a ty ...