Home  >  Q&A  >  body text

Laravel/Vite/Inertiajs can't seem to import pages from a subdirectory (in my pages folder)

When I put the Register page into the pages folder it looks like this:

/pages
   - Register.vue

Then everything works fine and the page loads, but when I put the Register page into the auth folder, like this:

/pages
   /auth
      - Register.vue

It doesn't work, this is the error I see when I open the console:

dynamic-import-helper:7 Uncaught (in promise) Error: Unknown variable dynamic import: ./pages/auth/Register.vue
    at dynamic-import-helper:7:96
    at new Promise (<anonymous>)
    at default (dynamic-import-helper:6:12)
    at resolve (app.js:5:22)
    at e2.h2 [as resolveComponent] (createInertiaApp.js:8:52)
    at n2.setPage (router.ts:378:33)
    at router.ts:323:19

Does anyone know why this doesn't work?

This is my vite.config.js code:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
    plugins: [
        vue(),
        laravel({
            input: ['resources/css/app.css', 'resources/js/app.js'],
            refresh: true,
        }),
    ],
});

This is my app.js code:

import {createApp, h} from 'vue';
import {createInertiaApp} from "@inertiajs/inertia-vue3";

createInertiaApp({
    resolve: name => import(`./pages/${name}.vue`),
    setup({el, app, props, plugin}) {
        createApp({render: () => h(app, props)})
            .use(plugin)
            .mount(el)
    }
});

I tried changing ${name} to authentication/registration only and then it worked? But this isn't really a solution.

This is the method I call to render the Register page:

public function register(): Response|ResponseFactory
{
    return Inertia::render('auth/Register');
}

P粉674876385P粉674876385298 days ago462

reply all(1)I'll reply

  • P粉054616867

    P粉0546168672023-12-27 10:06:26

    I had the same problem and I fixed it by rewriting it as per Inertia's documentation.

    I'm on @inertiajs/react": "^1.0.2" and my code looks like this:

    import { createRoot } from 'react-dom/client';
    import { createInertiaApp } from '@inertiajs/react';
    
    const createApp = () =>
      createInertiaApp({
        resolve: (name) => {
          const pages = import.meta.glob('./pages/**/*.tsx', { eager: true });
          const page = pages[`./pages/${name}.tsx`];
          return page;
        },
        setup({ el, App, props }) {
          createRoot(el).render(<App {...props} />);
        },
      });
    
    export default createApp;

    import.meta.glob is vite-built-in feature which will pre-build all components found in this glob pattern and store them in an array. You can then access the page (module) that needs to be rendered from that array and return it in the resolve method.

    hope it helps you!

    reply
    0
  • Cancelreply