How to get input key in transform or transformIndexHtml in Vite or Rollup?

I want to make a Vite plugin for file routers. I can’t find the specific plugin in Awesome Vite and Rollup Awesome. Or maybe I am too lazy to curated one-by-one.

My problem is Rollup Input can give a name for the file in input option. It would also be use to pairing output to targeted entry file. But, how could I get this current transformation name in transform by Rollup or transformIndexHtml by Vite?

Here are example of code:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
import Inspect from 'vite-plugin-inspect'
import process from "process"

// https://vitejs.dev/config/
export default defineConfig({
  build: {
    input: {
      "about/know-me": "template/default.html",
      "about/company": "template/default.html",
    },
    output: [
      {
        name: "about/know-me",
        entryFilename: "about/know-me.html",
      },
      {
        name: "about/company",
        entryFilename: "about/company.html",
      },
    ],
  },

  plugins: [
    Inspect({
      build: true,
      outputDir: ".vite-inspect.local",
    }),

    {
      transform: {
        order: "pre",
        handler: (html, ctx) => {
          // 1. get current input name such as "about/know-me"
          // 2. replace %SCRIPT_SCR% to be "srx/about/know-me.tsx"
        return html;
        },
      },
    },
    react(),
  ],

  root: process.cwd(),
});

The above code are example what I want to achieve, If I can get the input key name, I could replace the %SCRIPT_SRC% inside html file. In full Idea, the plugin would indexing all script file ended with .page.tsx, and create the page .html from it. At the same time, it would also store a temporary config base on the file name, so I could call config[name].script. This was the idea.

In short, how could I get current in compiling input file, synchronized inside transform function, OR asynchronized via hooks?

What I want to achieve is this plugin:

Leave a Comment