?在給vite+vue3.0設(shè)置別名的時(shí)候,直接使用了__dirname這個(gè)內(nèi)置變量報(bào)錯(cuò)__dirname is not defined in ES module scope
報(bào)錯(cuò)原因:?
__dirname是commonjs規(guī)范的內(nèi)置變量。如果使用了esm,是不會(huì)注入這個(gè)變量的。
在commonjs中,注入了__dirname,__filename, module, exports, require五個(gè)內(nèi)置變量用于實(shí)現(xiàn)導(dǎo)入導(dǎo)出的能力。而在esm中,因?yàn)橐?guī)范已經(jīng)完全不一樣,故實(shí)現(xiàn)方式也是不一樣的。
在esm中,顯然模塊的導(dǎo)入導(dǎo)出使用export/import,自然不會(huì)再用exports /require,同理__dirname,__filename也有對應(yīng)的規(guī)范寫法。
解決的辦法:
import path from 'path'
import { fileURLToPath } from 'url'
const __filenameNew = fileURLToPath(import.meta.url)
const __dirnameNew = path.dirname(__filenameNew)
文章來源:http://www.zghlxwxcb.cn/news/detail-686656.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-686656.html
到了這里,關(guān)于報(bào)錯(cuò):__dirname is not defined in ES module scope的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!