### Leveraging Icons in Nuxt or Vue: A Step-by-Step Guide

I'm encountering an issue with Nuxt.js while attempting to implement the vue-fontawesome framework along with the @nuxtjs/fontawesome framework. Here is the specific error message:

[nuxt] [request error] Cannot read properties of undefined (reading 'component')
        at $id_c50a96b3 (./.nuxt/dist/server/server.mjs:3239:31)
        at async __instantiateModule__ (./.nuxt/dist/server/server.mjs:19193:3)
    

This snippet shows my code in nuxt.config.ts:

import { defineNuxtConfig } from 'nuxt'

    export default defineNuxtConfig({
      modules: [
        '@nuxtjs/fontawesome'
      ],

      fontawesome: {
        icons: {
          solid: ['faXmark']
        }
      }
    })
    

Below is the component where I intend to utilize the icon:

<template>
      <div :class="props.className">
        <font-awesome-icon icon="xmark" />
        <slot />
      </div>
    </template>
    

Interestingly, this error only surfaces when attempting to load the page, not during the initial execution.

Answer №1

For those in search of the best approach to working with icons, I highly recommend this solution by antfu: https://github.com/antfu/unplugin-icons. An in-depth article explaining the implementation can be found here.


If you're looking to integrate this solution with Nuxt3, here are the steps:

  • Ensure you are using Node v16 or later
  • Start a new Nuxt3 project:
    pnpm dlx nuxi init nuxt3-unplugin-icons
  • If you're using PNPM: pnpm i --shamefully-hoist
  • Add the package mentioned above: pnpm add -D unplugin-icons

Add the following code snippet to your nuxt.config.ts file:

// @ts-nocheck
import { defineNuxtConfig } from 'nuxt'
import Icons from 'unplugin-icons/vite'

export default defineNuxtConfig({
  vite: {
    plugins: [
      Icons({
        // an experimental feature ⬇️
        autoInstall: true
      })
    ]
  }
})

If you encounter issues with types, simply ignore them for now.


Once completed, visit icones.js, select your icon and note the format [collection-id]:[name]. For instance, fa6-solid:xmark.

In any .vue file, convert the format as shown: ~icons/fa6-solid/xmark.

<script setup>
import IconXmark from `~icons/fa6-solid/xmark`
</script>

<template>
  <icon-xmark style="font-size: 2em; color: blue" />
</template>

Your Nuxt3 project will automatically install the necessary packages.


The autoInstall feature is mostly reliable but not fully tested. In case of failures, search for

@iconify-json/[your collection id]
on npm (e.g., @iconify-json/fa6-solid).


Explore alternative icons with the following example:

<script setup>
import IconXmark from '~icons/fa6-solid/xmark'
import IconAccountBox from '~icons/mdi/account-box'
import TastyPizza from '~icons/noto-v1/pizza'
import IconPs from '~icons/ri/playstation-line'
</script>

<template>
  <icon-xmark style="font-size: 2em; color: blue" />
  <icon-account-box style="font-size: 2em; color: red" />
  <tasty-pizza style="font-size: 2em" />
  <icon-ps style="font-size: 2em" />
</template>

Customize these icons with CSS as desired:

Refer to my GitHub repository for a complete example if needed.

Stay tuned for the upcoming auto-import feature by subscribing to the GitHub PR.

You can also use these icons with dynamic components if you have a predefined list available for the bundler.

Answer №2

If you're looking for a way to easily integrate icons into your Nuxt project, consider using the latest package nuxt-icon developed by the CEO of NuxtLabs. This package is already being utilized in the nuxt3/content2 starter template available at content-wind.

Installation

npm install --save-dev nuxt-icon

yarn add --dev nuxt-icon

Configuring Nuxt 3

nuxt.config.ts

export default defineNuxtConfig({
   modules: ['nuxt-icon']
})

How to Use

To use this package, simply choose the icon you want from the collection on icones.js.org and copy its name. The package will handle the rest, fetching the icon and adding it to your code. With over 100k icons to choose from, the possibilities are endless.

<Icon name="logos:google-icon"></Icon>
<Icon name="logos:facebook"></Icon>
<Icon name="logos:apple" fill="#97a3b6"></Icon>

Answer №3

Custom SVG Icons Workflow

When I need to work with custom svg icons without using an icon framework, I often rely on vite-svg-loader. This solution is compatible with Nuxt 3 as well.

yarn add vite-svg-loader --dev

nuxt.config.ts

import svgLoader from 'vite-svg-loader'

export default defineNuxtConfig({
  vite: {
    plugins: [
      svgLoader({})
    ]
  }
})

Once the setup is complete, I create a reusable component for handling icons (components/IconLoader.vue):

<template>
  <component :is="icon" />
</template>

<script>
  const props = defineProps<{ name: string }>()
  const icon = computed(() => 
    defineAsyncComponent(() => import(`../assets/icons/${props.name}.svg`))
  )
</script>

With this custom icon loader component in place, I can easily display icons in other components (e.g. App.vue) :

<template>
  <icon-loader name="calendar" /> // assuming there is a calendar.svg file in your assets folder.
</template>

I typically source my icons from , which pair nicely with TailwindCSS.

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

Steps to decode a data URL into an image and render it on a canvas

With 3 canvases at my disposal, I decided to get creative. First, I cropped a region from canvas1 and showcased it on canvas2. Then, I challenged myself to convert the image in canvas2 into a URL and then reverse the process back to an image, all to be d ...

Using the cURL command to retrieve script content

Currently, I am utilizing cURL to access a specific website. However, I have encountered an issue where the content I require is generated by a script: function Button(){ ... document.getElementById("out").innerHTML = name; } <p id="out"></p> ...

Component variables do not update their values

I am facing an issue where the input field inside a component is not updating its value. Is there something that I have overlooked? By the way, I am using Vue 3. Child Component (input-form.vue) <template> <input type="text ...

Maximizing the potential of vue.js and firebase through proper directory organization

After installing firebase, the 'public' folder and 'index.html' are automatically created. I'm facing confusion regarding where to place the 'public' folder within the current vue project file structure. The 'localho ...

Tips for initializing and updating a string array using the useState hook in TypeScript:1. Begin by importing the useState hook from the

Currently, I am working on a React project that involves implementing a multi-select function for avatars. The goal is to allow users to select and deselect multiple avatars simultaneously. Here is what I have so far: export interface IStoreRecommendation ...

Updating the state using a function from another module

I have two modules, one called App and another where I define exportable variables. In one of the exportable variables, I am trying to update the state inside of the App module. Any advice on how I can achieve this would be greatly appreciated. import &quo ...

Mastering the art of scrolling to a specific element with angular-scroll

Currently implementing Angular Scroll and when reaching a specific page, I trigger a function to scroll to an ID. Encountering the following error in the code snippet below: TypeError: $document.scrollToElement is not a function initHelp(); function ...

Half the time, the Paypal button fails to load on Angular

My page has a recurring issue with a PayPal button that fails to load half the time. I recently experienced this problem when refreshing the page 30 times in a row – it alternated working properly for 9 times, then failed to load for 11 consecutive times ...

Discover the magic of using jQuery's .map() method with

$(function() { $('input[type=checkbox]:checked').map(function() { alert($("#chk_option").val()); $("#chk_option").val(this.value); }).get(); }); HTML code <div> <center> <form id="form_tarif" class="form-horizo ...

Receive an HTTP POST request within JavaScript without using Ajax in Symfony 4.1

Searching for a way to handle an event triggered by a PHP post, not through Ajax. I would like to show a spinner when the form is posted using PHP. In JavaScript, it's easy with code like this: $(document).on({ ajaxStart: function() { $('#p ...

Having trouble retrieving returned data after refetching queries using Apollo and GraphQL

I am able to track my refetch collecting data in the network tab, but I am facing difficulty in retrieving and using that data. In the code snippet below where I am handling the refetch, I am expecting the data to be included in {(mutation, result, ...res ...

Can the page count be reduced by subtracting the quantity of a specific class from it?

Just getting started with Vue and could use some guidance. I'm trying to figure out how to subtract the count of elements with a specific class (showClosed) from my total results. Is that something that can be done? I've managed to retrieve the ...

Vue.js is having trouble locating images

I am currently using Vue-CLI with the latest version of Vue (3.9.3), but I am facing an issue where Vue cannot locate my images. Below are some screenshots for reference. Why are the images not showing up? First image (Structure) Second image (template) ...

Using an image tag within a button element causes functionality issues with JavaScript on Chrome

Can anyone help me figure out why my button with an image isn't toggling a div's class in Chrome? It works fine in Firefox. Here is the codepen link for reference: https://codepen.io/luansergiomattos/pen/zydWyM This is the HTML code: <div cl ...

Using Discord.js to retrieve identical lines from a text file in a database

I've been working on a discord bot that is supposed to send a line from a .txt file to the message author via DM, then delete that specific line from the file. However, it seems to be sending the same line repeatedly. Any suggestions on how to resolve ...

How to resolve the error of "Objects are not valid as a React child" in NextJs when encountering an object with keys {children}

I am currently working on a nextjs application and I have encountered an issue with the getStaticPaths function. Within the pages folder, there is a file named [slug].tsx which contains the following code: import { Image } from "react-datocms"; i ...

Uncover the solution to eliminating webpack warnings associated with incorporating the winston logger by utilizing the ContextReplacementPlugin

When running webpack on a project that includes the winston package, several warnings are generated. This is because webpack automatically includes non-javascript files due to a lazy-loading mechanism in a dependency called logform. The issue arises when ...

Experimenting with jQuery Hover Functionality Using Jasmine Testing

I am exploring the best way to test a jQuery Hover action with Jasmine. Here's a snippet of my jQuery code: $('.class').hover( function() { $('#someid').hide(); }, function() { $('#someid').show(); } ); How can I si ...

"After clicking the button for the second time, the jQuery on-click function begins functioning properly

(Snippet: http://jsfiddle.net/qdP3j/) Looking at this HTML structure: <div id="addContactList"></div> There's an AJAX call that updates its content like so: <div id="<%= data[i].id %>"> <img src="<%= picture %&g ...

Exploring various ways to implement HTTP GET requests within the PrimeVue DatatableUsing a mix

I am facing a challenge where I need to use different GET requests to populate my Datatable with data from separate tables in the Database. Despite trying different approaches, I am unable to figure out how to make this work successfully. I have realized t ...