search

Home  >  Q&A  >  body text

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

I have a question "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!

P粉642919823P粉642919823412 days ago821

reply all(1)I'll reply

  • P粉413307845

    P粉4133078452023-11-04 00:56:46

    As the error indicates, __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()

    reply
    0
  • Cancelreply