Coder Social home page Coder Social logo

astro-icon's Introduction

Astro Icon

This Astro integration provides a straight-forward Icon component for Astro.

Why Astro Icon

Installation

Quick Install

The astro add command-line tool automates the installation for you. Run one of the following commands in a new terminal window. (If you aren't sure which package manager you're using, run the first command.) Then, follow the prompts, and type "y" in the terminal (meaning "yes") for each one.

# Using NPM
npx astro add astro-icon
# Using Yarn
yarn astro add astro-icon
# Using PNPM
pnpm astro add astro-icon

If you run into any issues, feel free to report them to us on GitHub and try the manual installation steps below.

Manual Install

First, install the astro-icon package using your package manager. If you're using npm or aren't sure, run this in the terminal:

npm install astro-icon

Then, apply this integration to your astro.config.* file using the integrations property:

astro.config.mjs

import { defineConfig } from "astro/config";
import icon from "astro-icon";

export default defineConfig({
  integrations: [icon()],
});

Usage

Astro Icon is ready to use, with zero additional configuration. The included Icon component allows you to inline svgs directly into your HTML. Repeasted

Local Icons

By default, Astro Icon supports custom local svg icons. They are optimized with svgo automatically with no extra build step. See "A Pretty Good SVG Icon System" from CSS Tricks.

  1. Create a directory inside of src/ named icons/.
  2. Add each desired icon as an individual .svg file to src/icons/
  3. Reference a specific icon file using the name prop.
---
import { Icon } from 'astro-icon/components';
---

<!-- Loads the SVG in `/src/icons/filename.svg` -->
<Icon name="filename" />

Iconify Icons

Astro Icon also supports Iconify icon sets out-of-the-box.

  1. Find an Icon Set to use on the Iconify Icon Sets website
  2. Install the package (eg. npm i -D @iconify-json/mdi)
  3. Reference a specific icon using the name prop with (eg. mdi:account)
---
import { Icon } from 'astro-icon/components'
---

<!-- Automatically fetches and inlines Material Design Icon's "account" SVG -->
<Icon name="mdi:account" />

Props

The Icon component allows these custom properties:

interface Props extends HTMLAttributes<"svg"> {
  /**
   * References a specific Icon
   */
  name: string;
  title?: string;
  size?: number;
  width?: number;
  height?: number;
}

The Icon also accepts any global HTML attributes and aria attributes. They will be forwarded to the rendered <svg> element.

See the Props.ts file for more details.

Styling

Styling your icons is straightforward. Any styles can be targeted to the [data-icon] attribute selector. If you want to target a specific icon, you may target it by name using [data-icon="filename"].

---
import { Icon } from 'astro-icon/components';
---

<style lang="css">
    [data-icon] {
        color: blue;
        /* OR */
        fill: blue;
    }
    [data-icon="annotation"] {
        color: red;
        /* OR */
        fill: red;
    }
</style>

<Icon name="adjustment" /> <!-- will be blue -->
<Icon name="annotation" /> <!-- will be red -->

<!-- Example using Tailwind to apply color -->
<Icon name="annotation" class="text-red-500" /> <!-- will be red-500 -->

Using with Frameworks

Astro Icon can be used with other frameworks utilizing the slot element. You can read more about how to use Slots in Astro here. Passing Children to Framework Components

Configuration

Configuring the Integration

The Astro Icon integration has its own options for controlling the Icon component. Change these in the astro.config.mjs file which is where your project's integration settings live.

config.include

For users with a project using output: 'server' or output: 'hybrid', it is highly recommended to configure the exact icons that should be included in the server bundle. By default, every icon in the set will be bundled into the server JavaScript.

To filter the exact Iconify icons that should be included, set an array of allowed icons inside of the include object. Only these icons will be bundled.

astro.config.mjs

import { defineConfig } from "astro/config";
import icon from "astro-icon";

export default defineConfig({
  // ...
  integrations: [
    icon({
      include: {
        mdi: ["*"], // (Default) Loads entire Material Design Icon set
        mdi: ["account"], // Loads only Material Design Icon's "account" SVG
      },
    }),
  ],
});

config.iconDir

If you want to use a different custom svg icon directory instead of the default src/icons/, specify that file path using config.iconDir

import { defineConfig } from "astro/config";
import icon from "astro-icon";

export default defineConfig({
  // ...
  integrations: [
    icon({
      iconDir: "src/assets/icons",
    }),
  ],
});

config.svgoOptions

If you want to behavior of .svg optimization, you can configure the svgo options rather than using the defaults. Read more about the available svgo options here.

import { defineConfig } from "astro/config";
import icon from "astro-icon";

export default defineConfig({
  // ...
  integrations: [
    icon({
      svgoOptions: {
        multipass: true,
        plugins: [
          {
            name: "preset-default",
            params: {
              overrides: {
                // customize default plugin options
                inlineStyles: {
                  onlyMatchedOnce: false,
                },

                // or disable plugins
                removeDoctype: false,
              },
            },
          },
        ],
      },
    }),
  ],
});

Migrating to v1

astro-icon v1 contains a number of breaking changes. Please reference the Migrate to astro-icon v1 guide to update from older versions of astro-icon.

Contributing

You're welcome to submit an issue or PR!

Changelog

See CHANGELOG.md for a history of changes to this integration.

astro-icon's People

Contributors

arch-fan avatar avgvstvs96 avatar chuygil avatar dwightjack avatar fredkschott avatar gavar avatar germanz avatar github-actions[bot] avatar jasikpark avatar kripod avatar liruifengv avatar magicbyt3 avatar matthewp avatar mingjunlu avatar natemoo-re avatar rafidmuhymin avatar stramel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

astro-icon's Issues

Build errors when using Icon component

I'm using Icon with a minimal Astro setup, but hitting errors during build that prevent usage.

Here's a repo with an isolated example and all the details in this issue https://github.com/tylergaw/astro-icon-issue-1-example

The setup

  • Astro 0.21.10
  • astro-icon 0.2.1
  • node 14.6.0 (also tried 16.9.1 with same results)

I've copied the main bits from the demo here https://github.com/natemoo-re/astro-icon/tree/main/demo and just slimmed it down to:

In src/pages/index.astro:

---
import { Icon } from 'astro-icon';
---
<html lang="en">
<head>
  <meta charset="utf-8" />
  <link rel="icon" type="image/x-icon" href="/favicon.ico" />
  <meta name="viewport" content="width=device-width" />
  <title>Welcome to Astro</title>
</head>
  <body>	
    <Icon name="adjustment" />
  </body>
</html>

And then running yarn build or running with yarn start produces a few errors.

There's more to all of these, but the most relevant bits seem like:

[vite] Error when evaluating SSR module /node_modules/svgo/lib/svgo-node.js?v=5f848506:
ReferenceError: require is not defined
  at /node_modules/svgo/lib/svgo-node.js?v=5f848506:3:12
...
[vite] Error when evaluating SSR module /node_modules/astro-icon/lib/utils.ts:
ReferenceError: require is not defined
  at /node_modules/svgo/lib/svgo-node.js?v=5f848506:1:12
...
[vite] Error when evaluating SSR module /node_modules/astro-icon/index.ts?v=5f848506:
TypeError: Line must be greater than or equal to 1, got -1
  at BasicSourceMapConsumer.SourceMapConsumer_findMapping [as _findMapping]
...

Updating to `svgo@3` causes issues

I updated astro-compress to its latest 1.1.1 release and this broke icons as it brought with it svgo@3. Not fully sure it's an issue with astro-icon, might very likely be upstream at Astro itself, but I cannot guarantee it...

This made a change on the cleanupIDs plugin, which is now called cleanupIds.

I have now pinned astro-compress to 1.0.12 especially as the 1.1 feature wasn't of interest in my case, but it might be worth updating this package to support svgo@3.

Reference for svgo@3: https://github.com/svg/svgo/releases/tag/v3.0.0.

file:///Users/matteo/GitHub/[repo]/dist/entry.mjs?time=1666904273871:1746
      throw new Error(`[astro-icon] Unable to load icon "${name}"!
            ^

Error: [astro-icon] Unable to load icon "wifi-slash-regular"!
Error: Unknown builtin plugin "cleanupIDs" specified.
    at file:///Users/matteo/GitHub/[repo]/dist/entry.mjs?time=1666904273871:1746:13
    at async renderToIterable (file:///Users/matteo/GitHub/[repo]/dist/entry.mjs?time=1666904273871:745:21)
    at async renderAstroComponentInline (file:///Users/matteo/GitHub/[repo]/dist/entry.mjs?time=1666904273871:973:24)
    at async renderChild (file:///Users/matteo/GitHub/[repo]/dist/entry.mjs?time=1666904273871:671:5)
    at async AstroComponent.[Symbol.asyncIterator] (file:///Users/matteo/GitHub/[repo]/dist/entry.mjs?time=1666904273871:703:7)
    at async renderAstroComponent (file:///Users/matteo/GitHub/[repo]/dist/entry.mjs?time=1666904273871:714:20)
    at async renderAstroComponentInline (file:///Users/matteo/GitHub/[repo]/dist/entry.mjs?time=1666904273871:974:9)
    at async renderChild (file:///Users/matteo/GitHub/[repo]/dist/entry.mjs?time=1666904273871:671:5)
    at async AstroComponent.[Symbol.asyncIterator] (file:///Users/matteo/GitHub/[repo]/dist/entry.mjs?time=1666904273871:703:7)
    at async renderAstroComponent (file:///Users/matteo/GitHub/[repo]/dist/entry.mjs?time=1666904273871:714:20)

Move "[astro-icon] No sprites found ..." warnings to debug level

Context

It is therefore good to have deep insights what is going on inside astro-icon package, but it could be opted-out by default, and possible to opt-in when needed.

Currently astro-icon does console.log for warning:

console.log(`[astro-icon] No sprites found while rendering "${pathname}"`);

Astro (and Vite) does a good job by utilising https://github.com/debug-js/debug package, so any debugging can be revealed with DEBUG=... variable.

During astro build we do get many occurencies of:

[astro-icon] No sprites found while rendering "..."

even though sprites are used in only one page in whole project. Getting so many messages seems simply excessive.

TODO

  • Move debugging related messages to be opt-out by default, but possible to reveal on demand

`heroicons:user` is not loading showing a blank box

Might be there is some APIs changes needed to make it work.

Currently it's just heroicons:user not working, Hope you got some time to check into the issue.

Hope it helps to work with newer packages, thanks for such a great package.

think about merging this effort with unplugin-icons

iconify is the go-to option for icons. It would be great to have a canonical way of using such items in astro.
To the best of my understanding, unplugin-icons would be the best place to create such canonical solution.

I already opened a feature request over there unplugin/unplugin-icons#154

How do you think about mergin astro-icon into unplugin-icons?

Feature Request: option to normalize CSS & IDs

Problem

Many icons are optimized using SVGO which is very good at compression! But the side effect is that it will minify classes and IDs, like so:

<svg><style>.a{fill:#fc6d26}</style><path class="a" d="
<svg><defs><linearGradient id="a">

Even if icons aren’t optimized with SVGO at all, there’s still a really good chance of class & ID conflicts if a sprite sheet is big enough (id="Layer_1" is suspect). Any conflict at all will likely mean the icon displays incorrectly.

API

Unsure about the API (should this be default behavior? configurable? dunno!)

Solution A

One solution would be to inline <style>s, e.g. (which is an SVGO setting, I believe):

- <svg><style>.a{fill:#fc6d26}</style><path class="a" d="…
+ <svg><path fill="#fc6d26" d="…">

But that still leaves IDs!

Solution B

Probably a better solution is to not transform anything, but simply prefix all classes and IDs within an SVG, e.g.:

<svg><style>.astroicon-icon-github-a{fill:#fc6d26}</style><path class="a" d="
<svg><defs><linearGradient id="astroicon-icon-github-a">

(prefix can match the SVG IDs; not important)

Other

  • I am willing to create a PR for this

Simplify `Props` with ` astroHTML.JSX.SVGAttributes`

Hello!

Maybe this:

/// <reference types="astro/astro-jsx" />

export interface Props extends astroHTML.JSX.SVGAttributes {
 ...
}

Could now simplify the Props part of this component? With the benefit of Astro ecosystem homogenization.

Heroicons not found?

Looks like https://api.astroicon.dev/v1/heroicons/<anything> returns Not Found: Pack "heroicons".

Maybe it has to do with their release of heroicons v2 this week?

Allow svgs with titles to keep them after svgo optimization

Thanks for this plugin! I have a suggestion:

It looks like svgo's removeTitle plugin is enabled by default.

While I learned from #36 that there is a prop for adding a title to an svg, I think it would be helpful to permit svg's that already have a title embedded to keep their titles, without needing to re-add them.

Perhaps either svgo's removeTitle plugin could be optionally disabled, or perhaps there could be a prop for astro-icon to preserve any already-existing title?

Inserting an `<Icon />` element into `map` will fail on first render & all build

Bug

Adding an Icon component as part of a map operation will fail all but the first icon

Code sample

{[1,2,3].map(() => <Icon name="bi:stars" /> )}

Errors

Dev

on first dev load (2/3 icons missing, everything works after a refresh):

Error: <Icon pack="bi" name="stars" /> did not return an icon!
    at Module.load [as default] (/node_modules/astro-icon/lib/utils.ts:140:13)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
    at async eval (/node_modules/astro-icon/lib/Icon.astro:25:17)
    at async renderToString (/node_modules/astro/dist/runtime/server/index.js?v=b26a95c3:296:21)
    at async Module.renderComponent (/node_modules/astro/dist/runtime/server/index.js?v=b26a95c3:118:20)
    at async _render (/node_modules/astro/dist/runtime/server/index.js?v=b26a95c3:44:11)
    at async renderAstroComponent (/node_modules/astro/dist/runtime/server/index.js?v=b26a95c3:330:20)
    at async _render (/node_modules/astro/dist/runtime/server/index.js?v=b26a95c3:53:12)
    at async Promise.all (index 1)
    at async _render (/node_modules/astro/dist/runtime/server/index.js?v=b26a95c3:46:13)
Error: <Icon pack="bi" name="stars" /> did not return an icon!
	at...
	...

image

Build

Build does not finish, errors out with:

[astro-icon] Unable to load icon "bi:stars"!
Error: <Icon pack="bi" name="stars" /> did not return an icon!
Error: [astro-icon] Unable to load icon "bi:stars"!
Error: <Icon pack="bi" name="stars" /> did not return an icon!
 ELIFECYCLE  Command failed with exit code 1.

CodeSandbox repro

(server controls > restart sandbox > reload the live preview to trigger)
https://codesandbox.io/s/hungry-pike-xrsre?file=/src/pages/index.astro:478-524

Unescaped HTML content found inside expression warning

I recently upgraded to astro@next (0.23.0-next.2) and after starting the dev server I get the following warning:

*I am only using the <Icon /> component in my site

Unescaped HTML content found inside expression!

The next minor version of Astro will automatically escape all
expression content. Please use the `set:html` directive.

Expression content:
<path fill="currentColor" d="M22.46 6c-.77.35-1.6.58-2.46.69.88-.53 1.56-1.37 1.88-2.38-.83.5-1.75.85-2.72 1.05C18.37 4.5 17.26 4 16 4c-2.35 0-4.27 1.92-4.27 4.29 0 .34.04.67.11.98C8.28 9.09 5.11 7.38 3 4.79c-.37.63-.58 1.37-.58 2.15 0 1.49.75 2.81 1.91 3.56-.71 0-1.37-.2-1.95-.5v.03c0 2.08 1.48 3.82 3.44 4.21a4.22 4.22 0 0 1-1.93.07 4.28 4.28 0 0 0 4 2.98 8.521 8.521 0 0 1-5.33 1.84c-.34 0-.68-.02-1.02-.06C3.44 20.29 5.7 21 8.12 21 16 21 20.33 14.46 20.33 8.79c0-.19 0-.37-.01-.56.84-.6 1.56-1.36 2.14-2.23z"/>

I'm assuming this warning is coming from here right?

So once features from 0.23.0-next.2 are in the latest release the following can be changed in the Icon component:

From:

<svg {...props} astro-icon={name}>{title ? (<title>{title}</title>) : ''}{innerHTML}</svg>

To:

<svg {...props} astro-icon={name} set:html={innerHTML}>{title ? (<title>{title}</title>) : ''}</svg>

I could be completely misunderstanding this, but if not I would be happy to make these changes in the future!

Google Material Symbols not Found

Code : <Icon name="material-symbols:10k" />

Error: Not Found: pack "material-symbols"
    at request (/node_modules/astro-icon/lib/resolver.ts:17:13)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

Icons outdated

Using the icon names from the websites listed on readme often gets you a square instead of the actual icon.

I believe the icons are outdated.

Offline mode

I am using a build system for reproducible builds. This does not allow for internet access under normal circumstances.

I can circumvent this restriction by offloading the internet access to other buildsteps, though these are required to have a fixed output then.

Therefore I'd like to maintain a list of SVGs to be used in an extra file and using that to "prefetch" them into a cache location and then just tell astr-icon which cache folder to use, such that I can still use name="mdi:account" or pack="mdi" name="account" syntaxes.

Adding just names like that to a list is much easier and less error prone to me, than having to manually copy the SVGs to /src/icons, also the necessary rename on filesystem and in code takes removes the relationship to the website that mdi:account gives me.

Use in non-astro components?

Can this be used in components other than .astro? Like .svelte, .vue etc.

I'm getting an error but not sure what the exact reason for this is

Invalid HTML due to astro-icon attribute

Custom attributes without the data- prefix are non-standard, and disfavored by validators like Nu Html Checker (see below). It would be a breaking change, but replacing astro-icon with data-astro-icon (or data-icon) would be an improvement.

afbeelding

Idea: Callable script to load icon packs or dynamic icons

If you have a ./src/icons/foo.ts file that default-exports function get(name: string): string which returns a raw svg string for a given icon name, you can call said function with <Icon name="foo::some-icon" />.

This way a user can use icon packs like bootstrap-icons without having to either have 15k files or manually copy over new ones any time they need one.
It could also be used to generate procedural/dynamic/random icons like user avatars. (ex. the dicebear avatars package returns an svg string)

One drawback may be that (I believe) there is no way to do spritesheets with this approach, as the component can't tell what svgs will get used to load them in. But it may be possible to have <Spritesheet pack="foo" icons={["some-icon-1", ...]} /> if someone really wants to use it.

(I am open to try and implement it myself, looks like I should just use a different import @ https://github.com/natemoo-re/astro-icon/blob/main/packages/core/lib/utils.ts if :: is detected)

`svgo` and SSR

svgo is a Node.js-only package, thus, it doesn't work in the brand-new environments that Astro SSR supports (e.g. Netlify/Vercel Edge, Deno, Cloudflare workers).

Is there any other option that supports more environments? Or there could be a way to disable svgo altogether so Astro can build successfully?

Cache Icons for offline use

Thanks for creating such a great astro component.

Is it possible to cache icons so site development can continue if the internet cuts out/becomes unavailable?

Bug: Sprite.Provider/Spritesheet breaks pages where sprites are not used

Sprite.Provider breaks pages that do not use any sprites.

Steps to reproduce

Create an astro page with a Sprite.Provider but with no Sprite components as children

Observed behavior

The page fails to build with a misleading "<SpriteSheet> should be the very last child of the page's <body>!" error

Desired behavior

The page builds and renders properly

Workaround

Don't render the Sprite.Provider on pages (which may be difficult if placed in a layout component), or add a hidden sprite to each page

Style SVG children

As I understand, you can only style the top-level <svg> element, the one with data attribute [astro-icon] like below:

<style>
    [astro-icon] {
        color: blue;
        /* OR */
        fill: blue;
    }
</style>

Targeting child of the SVG, like path element won't work:

<style lang="css">
  /* Nothing happens here*/
    [astro-icon] path {
        fill: blue;
    }
</style>

I would like to know if this is the intended behavior of Astro Icon. Is there any plan to allow for styling SVG children?

Using external src file

It would be great to use an external file, let's say from a JSON file.

<Icon name="external" src="https://...">

From version 0.7.1 `<Sprite.Provider>` inject scripts and styles inside own place (astro build phase)

Here example:

---
import './app.css'
---
<html>
  <head>
  </head>
  <body>
    <Sprite.Provider>
      <Sprite pack="mdi" name="close" />
    </Sprite.Provider>
  </body>
</html>

From version 0.7.0:

<html>
  <head>
    <link href="/_astro/style.0dedd145.css" rel="stylesheet">
  </head>
  <body>
    <svg aria-hidden="true" astro-icon-spritesheet="" style="position:absolute;width:0;height:0;overflow:hidden">...</svg>
  </body>
</html>

From version 0.7.1:

<html>
  <head>
  </head>
  <body>
    <link href="/_astro/style.0dedd145.css" rel="stylesheet">
    <svg aria-hidden="true" astro-icon-spritesheet="" style="position:absolute;width:0;height:0;overflow:hidden">...</svg>
  </body>
</html>

Styles and scripts always injected at <Sprite.Provider> place, which lead to broken https://hotwired.dev/ usage - on each page body contain same css and js files, which need to re-apply in browser again. Inject directly to <head> not allow syntax (this is invalid):

<html>
  <head>
    <Sprite.Provider>
  </head>
  <body>
      <Sprite pack="mdi" name="close" />
    </Sprite.Provider>
  </body>
</html>

Recommended tailwind styling?

First of all, awesome plugin!

I'm like using tailwind but am not sure which way is best to style the icons. Something like below?

---
import { Icon } from 'astro-icon';
---

<style lang="css">
    [astro-icon] {
        @apply text-blue
        /* OR */
        @apply text-blue
    }
    [astro-icon="annotation"] {
        @apply text-red
        /* OR */
        @apply text-red
    }
</style>

<Icon name="adjustment" /> <!-- will be blue -->
<Icon name="annotation" /> <!-- will be red -->

If so, might be useful to take up in the README.

I think it will be a great addition to add a 'class' prop. Would make things a lot easier when using tailwind and protentially cleaner in some cases when using regular styles.

Cannot load SVG icon although the files is there

I have an SVG icon that I want to use. I out the SVG file in /src/icons in the project but when rendering it doesn't work.

Here is the error

Error: [astro-icon] Unable to load "/src/icons/mylogo.svg". Does the file exist? at Module.load [as default] (/node_modules/astro-icon/lib/utils.ts:182:13) at eval (/node_modules/astro-icon/lib/Icon.astro:26:52) at Module.renderToIterable (/node_modules/astro/dist/runtime/server/render/astro.js:76:27) at renderAstroComponentInline (/node_modules/astro/dist/runtime/server/render/component.js:75:52) at renderAstroComponentInline.next (<anonymous>) at Module.renderChild (/node_modules/astro/dist/runtime/server/render/any.js:25:5) at processTicksAndRejections (node:internal/process/task_queues:96:5) at async AstroComponent.[Symbol.asyncIterator] (/node_modules/astro/dist/runtime/server/render/astro.js:37:7) at async Module.renderAstroComponent (/node_modules/astro/dist/runtime/server/render/astro.js:45:20) at async renderChild (/node_modules/astro/dist/runtime/server/render/any.js:23:5)

The library does not work with ssr deno server

Hello
This issue is related to #35
I have an astro project with deno server, and when dev processing, the project works properly without any compile error,
But when compiling to build (npm run build), it gives me the folowing error

> npm run build

> @example/[email protected] build
> astro build

07:16:14 [build] output target: server
07:16:14 [build] Collecting build info...
07:16:14 [build] Completed in 22ms.
07:16:14 [build] Building server entrypoints...
[commonjs--resolver] Cannot bundle Node.js built-in "os" imported from "node_modules\svgo\lib\svgo-node.js". Consider disabling ssr.noExternal or remove the built-in dependency.
file: ..../node_modules/svgo/lib/svgo-node.js
 error   Cannot bundle Node.js built-in "os" imported from "node_modules\svgo\lib\svgo-node.js". Consider disabling ssr.noExternal or remove the built-in dependency.
  File:
  ..../node_modules/svgo/lib/svgo-node.js

because its based on node js libraries, i tried to found some alertnatives with native javascript or works on deno, but my knowledge is not that good .
any help or hints ? i can contribute with a PR to make it depends on pure javascript
thanks in advance

Icon not found

Got the following error

Error: Not Found: "newspaper" in pack "charm"
    at request (/node_modules/astro-icon/lib/resolver.ts:17:13)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

However, I've checked from the charm icon pack that it exists.

Sporadic crash of Astro dev server with error in astro/icon

The following happens every once in a while (1 out of 4-5 times) when starting or restarting the Astro dev server.

Cannot convert undefined or null to object
/node_modules/.pnpm/[email protected]/node_modules/astro-icon/index.ts:25:23
TypeError: Cannot convert undefined or null to object
    at Function.assign (<anonymous>)
    at eval (/node_modules/.pnpm/[email protected]/node_modules/astro-icon/index.ts:25:23)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async instantiateModule (file:///workspaces/dooiy/node_modules/.pnpm/[email protected][email protected]/node_modules/vi

Error: Unknown builtin plugin "cleanupIDs" specified.

Hello,

since now I can't build my astro project anymore.
I get the following error:

 error   [astro-icon] Unable to load icon "carbon:phone-filled"!
  Error: Unknown builtin plugin "cleanupIDs" specified.

It doesn't matter which icon I am trying to load.

My package json:

{
  "name": "@example/basics",
  "type": "module",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "dev": "astro dev",
    "start": "astro dev",
    "build": "astro build",
    "preview": "astro preview",
    "astro": "astro"
  },
  "dependencies": {
    "@astrojs/image": "^0.12.1",
    "@astrojs/netlify": "^1.2.2",
    "@astrojs/partytown": "^1.0.2",
    "@astrojs/sitemap": "^1.0.0",
    "@astrojs/solid-js": "^1.2.3",
    "astro": "^1.6.15",
    "astro-compress": "^1.1.22",
    "astro-icon": "^0.8.0",
    "sharp": "^0.31.2",
    "solid-js": "^1.6.5"
  },
  "devDependencies": {
    "sass": "^1.55.0"
  }
}

My Code:

---
import { Icon } from 'astro-icon'
---
<Icon name="carbon:close" />

Not sure what's wrong. My last build was a few weeks ago and it worked fine then.

SpriteSheet doesn't detect icons used in components

Problem

It seems like the tracking system used by SpriteSheet to get a list of your used icons doesn't detect icons that are used in components. This worked before this tracking system was added

Exemple use case

I have a BaseLayout.astro file with <SpriteSheet/> at its end, that BaseLayout.astro has a <Socials> component that includes icons and it causes the following error: [astro-icon] <SpriteSheet> should be the very last child of the page's <body>! Is it currently placed before any <Sprite> components?

A solution could be to put <SpriteSheet/> in that <Socials /> component, however this is not possible as this <Socials> components is used multiple times throughout the Layout (once in the Header, once in the Footer, which incidentally are also separate components)

Potential solutions

If it isn't possible to make it detect icons used in components (I don't think it is from my exploration of building Astro components but I could be proved wrong?), it'd be great to at least be able to manually supply a list of icons to SpriteSheet to include

Minimal repro

https://stackblitz.com/edit/github-c5ox6n

No `simple-icons:pocketbase`

Despite it being listed as an icon:

image

I get this error:

Error: Not Found: "pocketbase" in pack "simple-icons"
    at request (/node_modules/astro-icon/lib/resolver.ts:17:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

image

Props like `stroke-width` are not passed down to `svg` element's children

Issue description

Props passed to Icon are only applied to the "top-level" svg element but not its children. I noticed this while working w/ Tabler icons. For example, when I tell Icon to use a stroke width of 1 and to use the color red, the emitted svg element shows both those properties but they're ignored by the contained path element. (See example below.)

I don't know whether that's by design but I was expecting my settings being passed down the chain. I understand that might not always be desirable, especially when it comes to multi-color SVGs etc. But is there a way to force the props down to the path etc.? If not, might such functionality (hidden behind a toggle) be a useful addition to astro-icon?

Possible way to do it: iterate over children, filter their attributes for those that correlate w/ a passed-in prop and replace those.

Input

<Icon
  name="tabler:brand-gitlab"
  size="48"
  stroke-linecap="square"
  stroke-linejoin="square"
  stroke-width={1}
  stroke="red"
/>

Expected output

Note: I've sorted the attributes for easier visual scanning.

<svg
  astro-icon="tabler:brand-gitlab"
  height="48"
  stroke-linecap="square"
  stroke-linejoin="square"
  stroke-width="1"
  stroke="red"
  viewBox="0 0 24 24"
  width="48"
  ><path
    d="m21 14-9 7-9-7L6 3l3 7h6l3-7z"
    fill="none"
    stroke-linecap="square"
    stroke-linejoin="square"
    stroke-width="1"
    stroke="red"></path>
</svg>

Actual output

Note: I've sorted the attributes for easier visual scanning.

<svg
  astro-icon="tabler:brand-gitlab"
  height="48"
  stroke-linecap="square"
  stroke-linejoin="square"
  stroke-width="1"
  stroke="red"
  viewBox="0 0 24 24"
  width="48"
  ><path
    d="m21 14-9 7-9-7L6 3l3 7h6l3-7z"
    fill="none"
    stroke-linecap="round"
    stroke-linejoin="round"
    stroke-width="2"
    stroke="currentColor"></path>
</svg>

Page doesn't load when using astro-icons with ssr

After some trying, it seems like using the @astrojs/node build output does not work with astro-icon. It causes the page to be stuck at loading when in a production build. It does work in normal yarn dev mode tho. There are no errors in the console while building or running the code with yarn preview which makes it hard to debug the issue and find the root of the problem

Font Awesome 6 packs don't work (fa6-solid, fa6-regular, fa6-brands)

When I try to use one of the fa6-* packs, e.g. like this:

---
import { Icon } from 'astro-icon'
---

<Icon pack="fa6-solid" name="twitter" />

I see this error message in the astro console:

Error: Not Found: pack "fa6-brands"
    at request (/node_modules/astro-icon/lib/resolver.ts:17:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async get (/node_modules/astro-icon/lib/resolver.ts:33:10)
    at async Module.load [as default] (/node_modules/astro-icon/lib/utils.ts:153:22)
    at async eval (/node_modules/astro-icon/lib/Icon.astro:22:17)
    at async AstroComponentInstance.render (/node_modules/astro/dist/runtime/server/render/astro/instance.js:36:7)
    at async Module.renderChild (/node_modules/astro/dist/runtime/server/render/any.js:30:5)

Direct usage of the API doesn't work too (listed below), all endpoints return a 404 response with a Not Found: pack "fa6-solid" message.

https://api.astroicon.dev/v1/fa6-solid
https://api.astroicon.dev/v1/fa6-regular
https://api.astroicon.dev/v1/fa6-brands

All the packs are present on Iconify and Icones.

` [astro-icon]` styling in a scoped component fails with `Unknown word`

Inputting any css styles with [astro-icon] on a scoped component fails...

src/components/my-component

<style>
...
  [astro-icon] {
      color="white";
    }

...
</style>

ERROR

 error   /mnt/site/src/components/my-component.astro?astro&type=style&lang.css:8:7: Unknown word
    at Input.error (/mnt/site/node_modules/postcss/lib/input.js:148:16)
    at Parser.unknownWord (/mnt/site/node_modules/postcss/lib/parser.js:540:22)
    at Parser.other (/mnt/site/node_modules/postcss/lib/parser.js:164:12)
    at Parser.parse (/mnt/site/node_modules/postcss/lib/parser.js:72:16)
    at parse (/mnt/site/node_modules/postcss/lib/parse.js:11:12)
    at new LazyResult (/mnt/site/node_modules/postcss/lib/lazy-result.js:133:16)
    at Processor.process (/mnt/site/node_modules/postcss/lib/processor.js:28:14)
    at compileCSS (/mnt/site/node_modules/vite/dist/node/chunks/dep-8f5c9290.js:37635:10)
    at async transform (/mnt/site/node_modules/vite/dist/node/chunks/dep-8f5c9290.js:37186:55)
    at async preprocessStyle (file:///mnt/site/node_modules/astro/dist/vite-plugin-astro/compile.js:44:24)

Unable to load local Icons when using "--experimental-static-build" flag

thanks for making this very useful component.
unfortunately I noticed an issue with using the package with the new experimental build flag. this may be an issue with the new build process, or something wrong with the astro-icon.
of course user error on my end is always a possibility.
let me know if there is any additional information I can provide

  • works fine without the flag, works correctly with astro dev
  • crashes build when running astro build cmd with the experimental build flag.
  • "svgo" is added to vite.ssr.external[]
  • when i click the link in the error to navigate to /src/icons/Wordmark.svg navigates to the correct SVG even though it claims to not be able to load it.
  • build completes, but servering the home page returns a 404
  • are there any specific ways i should format the svg? specific tags/layout within the svg?
  • this is the only obstacle preventing me from using the new build mode, so I will continue using the default astro build process until this is resolved.
  • just tried removing all other props height, class etc.. and error still occurs
---
import { Icon } from 'astro-icon' 
---
 <Icon name="Wordmark" height="42" class="mt-8" />

system config

Error

01:21 AM [build] Error rendering: Error: [astro-icon] Unable to load icon "Wordmark"!
Error: [astro-icon] Unable to load "/src/icons/Wordmark.svg". Does the file exist?
    at file:///home/andreclark/Documents/GitHub/lunarium/frontend/dist/assets/Default.de3d07fa.mjs:42344:13
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async renderToString (file:///home/andreclark/Documents/GitHub/lunarium/frontend/dist/assets/Default.de3d07fa.mjs:1688:21)
    at async renderComponent (file:///home/andreclark/Documents/GitHub/lunarium/frontend/dist/assets/Default.de3d07fa.mjs:1518:20)
    at async _render (file:///home/andreclark/Documents/GitHub/lunarium/frontend/dist/assets/Default.de3d07fa.mjs:1443:11)
    at async renderAstroComponent (file:///home/andreclark/Documents/GitHub/lunarium/frontend/dist/assets/Default.de3d07fa.mjs:1694:20)
    at async _render (file:///home/andreclark/Documents/GitHub/lunarium/frontend/dist/assets/Default.de3d07fa.mjs:1453:12)
    at async renderComponent (file:///home/andreclark/Documents/GitHub/lunarium/frontend/dist/assets/Default.de3d07fa.mjs:1513:20)
    at async _render (file:///home/andreclark/Documents/GitHub/lunarium/frontend/dist/assets/Default.de3d07fa.mjs:1443:11)
    at async renderAstroComponent (file:///home/andreclark/Documents/GitHub/lunarium/frontend/dist/assets/Default.de3d07fa.mjs:1694:20)
01:21 AM [build] Error rendering: Error: [astro-icon] Unable to load icon "Logo"!
Error: [astro-icon] Unable to load "/src/icons/Logo.svg". Does the file exist?
    at file:///home/andreclark/Documents/GitHub/lunarium/frontend/dist/assets/Default.de3d07fa.mjs:42344:13
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async renderToString (file:///home/andreclark/Documents/GitHub/lunarium/frontend/dist/assets/Default.de3d07fa.mjs:1688:21)
    at async renderComponent (file:///home/andreclark/Documents/GitHub/lunarium/frontend/dist/assets/Default.de3d07fa.mjs:1518:20)
    at async _render (file:///home/andreclark/Documents/GitHub/lunarium/frontend/dist/assets/Default.de3d07fa.mjs:1443:11)
    at async renderAstroComponent (file:///home/andreclark/Documents/GitHub/lunarium/frontend/dist/assets/Default.de3d07fa.mjs:1694:20)
    at async renderToString (file:///home/andreclark/Documents/GitHub/lunarium/frontend/dist/assets/Default.de3d07fa.mjs:1689:18)
    at async renderComponent (file:///home/andreclark/Documents/GitHub/lunarium/frontend/dist/assets/Default.de3d07fa.mjs:1518:20)
    at async _render (file:///home/andreclark/Documents/GitHub/lunarium/frontend/dist/assets/Default.de3d07fa.mjs:1443:11)
    at async renderAstroComponent (file:///home/andreclark/Documents/GitHub/lunarium/frontend/dist/assets/Default.de3d07fa.mjs:1694:20)

Feature Request: add possibility to globally define parameters such as height

As seen in a separate issue, one cannot easily style the height for all icons to "1em".

At least for me, this global font scaling is very important, as I expect my fonts to just work and not need extra individual tweaking.

I am not sure whether it is possible, but if so, it would be nice to have some global options for this.

Build failing on astro@^1.6.8 with "Error: [astro-icon] Unable to load icon"

Since updating to astro 1.6.8 (worked in .7), I'm getting this error:

generating static routes
--
07:56:29.563 | ▶ src/pages/index.astro
07:56:29.608 | file:///vercel/path1/.vercel/output/static/entry.mjs?time=1668840989319:2098
07:56:29.608 | throw new Error(`[astro-icon] Unable to load icon "${name}"!
07:56:29.608 | ^
07:56:29.608 |  
07:56:29.608 | Error: [astro-icon] Unable to load icon "tools/nvidia"!
07:56:29.609 | Error: Unknown builtin plugin "cleanupIDs" specified.
07:56:29.609 | at file:///vercel/path1/.vercel/output/static/entry.mjs?time=1668840989319:2098:13
07:56:29.609 | at async renderToIterable (file:///vercel/path1/.vercel/output/static/entry.mjs?time=1668840989319:903:21)
07:56:29.609 | at async renderAstroComponentInline (file:///vercel/path1/.vercel/output/static/entry.mjs?time=1668840989319:1476:24)
07:56:29.609 | at async renderChild (file:///vercel/path1/.vercel/output/static/entry.mjs?time=1668840989319:939:5)
07:56:29.609 | at async AstroComponent.[Symbol.asyncIterator] (file:///vercel/path1/.vercel/output/static/entry.mjs?time=1668840989319:861:7)
07:56:29.609 | at async renderAstroComponentInline (file:///vercel/path1/.vercel/output/static/entry.mjs?time=1668840989319:1477:9)
07:56:29.609 | at async renderChild (file:///vercel/path1/.vercel/output/static/entry.mjs?time=1668840989319:939:5)
07:56:29.609 | at async AstroComponent.[Symbol.asyncIterator] (file:///vercel/path1/.vercel/output/static/entry.mjs?time=1668840989319:861:7)
07:56:29.609 | at async renderAstroComponent (file:///vercel/path1/.vercel/output/static/entry.mjs?time=1668840989319:872:20)
07:56:29.610 | at async renderChild (file:///vercel/path1/.vercel/output/static/entry.mjs?time=1668840989319:935:5)
07:56:29.610 | at async renderChild (file:///vercel/path1/.vercel/output/static/entry.mjs?time=1668840989319:931:5)
07:56:29.610 | at async renderSlot (file:///vercel/path1/.vercel/output/static/entry.mjs?time=1668840989319:961:22)
07:56:29.642 | Error: Command "npm run build" exited with 1

I've tried all the new versions of astro (up to .10), along other updates or without, but to no avail.
It seems to break with the other icons as well; they are stored in the repo itself and called as such:

---
import { Icon } from "astro-icon";
---
        <Icon
          class="h-12 filter grayscale-[80%] hover:grayscale-0 transition duration-500 ease-in"
          name="tools/nvidia"
          alt="NVIDIA"
        />

File path being src\icons\tools\nvidia.svg

If this has to do with astro itself, I can create an issue on their repo. Thanks!

Improve Documentation on Local Icon Pack

Hi!

While trying to create my own local icon package I noticed the docs for astro/icon don't reflect the latest changes in the import path here:
https://github.com/natemoo-re/astro-icon#local-icon-packs

import { createIconPack } from "astro-icon";

should be

import { createIconPack } from "astro-icon/pack";

according to the changelog.

Also, the following comment could be improved:

// Resolves `heroicons` dependency and reads SVG files from the `heroicons/outline` directory
export default createIconPack({ package: "heroicons", dir: "outline" });

Does this mean the icon will be searched for in src/icons/heroicons/outline?
I tried it like that but I'm getting a pretty long error message 😅

TypeError: String.prototype.startsWith called on null or undefined
at startsWith ()
at Proxy.pathToFileURL (node:internal/url:1474:20)
at eval (/node_modules/astro-icon/lib/createIconPack.ts:16:53)
at Module.load [as default] (/node_modules/astro-icon/lib/utils.ts:156:28)
at eval (/node_modules/astro-icon/lib/Icon.astro:26:52)
at Module.renderToIterable (/node_modules/astro/dist/runtime/server/render/astro.js:79:27)
at renderAstroComponentInline (/node_modules/astro/dist/runtime/server/render/component.js:75:52)
at renderAstroComponentInline.next ()
at Module.renderChild (/node_modules/astro/dist/runtime/server/render/any.js:25:5)
at processTicksAndRejections (node:internal/process/task_queues:96:5)

I'm also missing the info whether it's possible to skip the dir parameter and put the icons directly into src/icons/heroicons/?

Missing icon packs

Hey, first of all, thanks for making this, this makes working with icons much easier for me.

Would it be possible to update @iconify/json?

"dependencies": {
"@iconify/json": "^1.1.439",
"@iconify/json-tools": "^1.0.10",
"etag": "^1.8.1"
},

I want to use an icon added in a newer version of a pack but @iconify/json is not on the latest version here.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.