hannoeru / vite-plugin-pages

File system based route generator for ⚡️Vite
MIT License
1.87k stars 128 forks source link

[Feature Request] Add option to specify import path as absolute path or keep relative path #492

Closed GoodbyeNJN closed 4 months ago

GoodbyeNJN commented 4 months ago

Description

I have a sample project with the project structure as follows:

./
├── index.html
├── src/
│   ├── main.tsx
│   └── pages/
│       └── App.tsx
└── vite.config.ts
// File: vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
import Pages from "vite-plugin-pages";
import Inspect from 'vite-plugin-inspect'

// https://vitejs.dev/config/
export default defineConfig({
  base: '/src/',
  plugins: [
    Inspect(),
    Pages({
      dirs: 'src/pages',
      importMode: 'sync',
    }),
    react(),
  ],
})
// File: main.tsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter, useRoutes } from 'react-router-dom'

import routes from '~react-pages'

import './index.css'

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <BrowserRouter>{useRoutes(routes)}</BrowserRouter>
  </React.StrictMode>,
)

The content of the automatically generated virtual:vite-plugin-pages/generated-pages?id=~react-pages virtual module is as follows:

// File: virtual:vite-plugin-pages/generated-pages?id=~react-pages
import React from "react";
import __pages_import_0__ from "/src/pages/App.tsx";

const routes = [{"caseSensitive":false,"path":"App","element":React.createElement(__pages_import_0__)}];

export default routes;

The import path is /src/pages/App.tsx, which is regarded as a relative path relative to the project root directory.

However, in vite's import-analysis plugin, the path will first be stripBase, see for details: https://github.com/vitejs/vite/blob/86cf1b4b497557f09a0d9a81dc304e7a081d6198/packages/vite/src/node/plugins/importAnalysis.ts#L298, this makes the module unable to be resolved.

In my understanding, virtual modules do not actually exist in the file system, so real files imported from the file system should use their absolute paths. Although vite also handles the use of relative paths when importing, edge cases like in this example cannot be avoided.

So I propose to add an option to specify the import path in the generated virtual module as an absolute path or a relative path

Suggested solution

Alternative

No response

Additional context

No response

Validations