最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ReferenceError: __dirname is not defined in ES module scope building script - Stack Overflow

programmeradmin0浏览0评论

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-ponents/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!

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-ponents/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!

Share Improve this question asked Oct 4, 2022 at 12:35 Chi Chi HuangChi Chi Huang 631 silver badge5 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

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

Add @types/node npm package

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

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

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

发布评论

评论列表(0)

  1. 暂无评论