ReferenceError: __dirname is not defined in ES module scope building script

6.2k views Asked by At

Im having a problem with "ReferenceError: __dirname is not defined in ES module scope" error

import path from 'path'
import { defineConfig } from 'vite'
import Vue from '@vitejs/plugin-vue'
import Pages from 'vite-plugin-pages'
import Layouts from 'vite-plugin-vue-layouts'
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import Unocss from 'unocss/vite'
import { campaign } from './package.json'



export default defineConfig({
  resolve: {
    alias: {
      '~/': `${path.resolve(__dirname, 'src')}/`,
    },
  },...

Can anyone provide a solution? Thank you so much!

3

There are 3 answers

6
Thermal_insulator On

As the error suggests, __dirname is not defined in the ES module scope.

Try this:

import url from 'url'

const __filename = url.fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

Now you can use __dirname in path.resolve()

2
Chi Chi Huang On

The solution is to update Node to the newest version. Vite dropped support for older ones. Thanks, everyone!

0
AnandShiva On

If you are facing the issue and recently installed module-alias Uninstalling module-alias and removing its related contents will fix the issues.