Skip to content

transform a js/jsx/ts string #20102

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
4 tasks done
huseeiin opened this issue May 24, 2025 · 1 comment
Open
4 tasks done

transform a js/jsx/ts string #20102

huseeiin opened this issue May 24, 2025 · 1 comment

Comments

@huseeiin
Copy link

Description

import { defineConfig, type Plugin } from "vite";
import { extname } from "node:path";

// convert svg to jsx
function svg(): Plugin {
  return {
    name: "svg",

    async transform(code, id) {
      if (extname(id) === ".svg") {
        return this.transformJsxOrTs(
          `export default () => ${decodeURIComponent(code)
            .replace('export default "data:image/svg+xml,', "")
            .replace('"', "")}`
        );
      }
    },
  };
}

Suggested solution

ability to run vite's internal transformer with all the user's plugins

Alternative

No response

Additional context

No response

Validations

@sapphi-red
Copy link
Member

You can achieve this by using a virtual module. Related: rollup/rollup#5903

import { defineConfig, type Plugin } from "vite";
import { extname } from "node:path";

// convert svg to jsx
function svg(): Plugin {
  return {
    name: "svg",
    resolveId() { /* TODO: impl */ },
    load() { /* TODO: impl */ },
    async transform(code, id) {
      if (id.includes('custom-svg')) {
        return `export default () => ${decodeURIComponent(code)
            .replace('export default "data:image/svg+xml,', "")
            .replace('"', "")}`
      }
      if (extname(id) === ".svg") {
        return `export { default } from ${JSON.stringify(`\0${id}?custom-svg&ext=.jsx`)}`
      }
    },
  };
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants