4

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!

4 Answers 4

7

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()

Sign up to request clarification or add additional context in comments.

6 Comments

Still getting the same error :(
Where did you write the code I gave in my answer?
import on top, defined var under all the imports
Try this: function dirname(meta) { return new URL("", meta.url).pathname; } const __dirname = dirname(import.meta); export default defineConfig({ resolve: { alias: { '~/': ${path.resolve(__dirname, 'src')}/, }, },...
Error: Cannot find module 'node:path' but you are on to something!
|
1

Add @types/node npm package

npm i -D @types/node --save-exact

Comments

0

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

2 Comments

This answer could be improved by adding links to change logs that document the change.
how new is new? I'm on v18.9.0 and still getting this
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.