unplugin / unplugin-icons

🤹 Access thousands of icons as components on-demand universally.
https://www.npmjs.com/package/unplugin-icons
MIT License
3.67k stars 131 forks source link

Add support for markojs #93

Closed dephiros closed 2 years ago

dephiros commented 2 years ago

Add support for markojs

I want to use this plugin with markojs but not sure how to contribute. @DylanPiercey or @ryansolid, would one you be able to point to the right direction?

DylanPiercey commented 2 years ago

@dephiros I think adding a new compiler like (https://github.com/antfu/unplugin-icons/tree/main/src/core/compilers) that looks something like this should do it:

import { Compiler } from './types'

export const MarkoCompiler = <Compiler>((svg: string) => {
  const openTagEnd = svg.indexOf('>', svg.indexOf('<svg '))
  const closeTagStart = svg.lastIndexOf('</svg')
  const openTag = `${svg.slice(0, openTagEnd)} ...input>`
  const content = `$!{\`${escapeTemplateLiteral(svg.slice(openTagEnd, closeTagStart))}\`}`
  const closeTag = svg.slice(closeTagStart)
  return `${openTag}${content}${closeTag}`
})

export function escapeTemplateLiteral(str: string): string {
  return str.replace(/\\.|[$`]/g, (m) => {
    switch (m) {
      case "$": return "&#36";
      case "`": return "&#96;";
      default: return m;
    }
  });
}

Essentially it just adds ...input to the root svg and uses $!{UNESCAPED_CONTENT} for the svg content.

dephiros commented 2 years ago

Thanks so much @DylanPiercey. I will try to test this out

userquin commented 2 years ago

@DylanPiercey I add your code and also add .marko extension to resolve marko component: https://markojs.com/docs/class- components/#single-file-components.

EDIT: you can see it here https://github.com/antfu/unplugin-icons/blob/feat/add-marko-compiler/src/index.ts#L24

@dephiros can you test it using this branch? https://github.com/antfu/unplugin-icons/tree/feat/add-marko-compiler

userquin commented 2 years ago

@DylanPiercey I think the plugin should return .js as extension, then on the compiler template render the code you provide to escape the svg html tag. It seems if adding .marko extension, marko vite plugin will try to resolve the component from the components directory and so it fails.

I only test it using vite. I have found multiple errors using marko vite example on Windows with node 15.