Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

anuzpandey's avatar

__dirname is not defined | Vite Error

Hello all. Im am using Laravel 10 with Vite and Vue 3. I am getting this error. I looked everywhere but could not find the solution.

[vite] Internal server error: __dirname is not defined
      at file:///Users/.../project-name/node_modules/.pnpm/[email protected][email protected]/node_modules/laravel-vite-plugin/dist/index.mjs:126:39

My vite.config.js

import fs from 'fs'
import {defineConfig} from 'vite'
import laravel from 'laravel-vite-plugin'
import vue from '@vitejs/plugin-vue'
import {homedir} from 'os'
import {resolve} from 'path'

let host = "travel-and-tours.test"

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

function detectServerConfig(host) {
    let keyPath = resolve(homedir(), `.config/valet/Certificates/${host}.key`)
    let certificatePath = resolve(homedir(), `.config/valet/Certificates/${host}.crt`)

    if (!fs.existsSync(keyPath)) {
        return {}
    }

    if (!fs.existsSync(certificatePath)) {
        return {}
    }

    return {
        hmr: {host},
        host,
        https: {
            key: fs.readFileSync(keyPath),
            cert: fs.readFileSync(certificatePath),
        },
    }
}
0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

The issue is that __dirname is not defined in ES modules. To fix this, you can use the import.meta.url property instead. Replace the following line in vite.config.js:

let keyPath = resolve(homedir(), `.config/valet/Certificates/${host}.key`)

with:

let keyPath = new URL(`.config/valet/Certificates/${host}.key`, import.meta.url).pathname

Do the same for certificatePath.

Please or to participate in this conversation.