Webpack編譯出錯(cuò)“Critical dependency: the request of a dependency is an expression”解決辦法
當(dāng)使用webpack進(jìn)行打包時(shí),如果遇到如下的require語(yǔ)法,
var mx = require("hpargxm".split("").reverse().join(""));
編譯將出錯(cuò),會(huì)提示“Critical dependency: the request of a dependency is an expression”
![]()
這種require語(yǔ)法是正確的,但webpack不能處理require中的表達(dá)式,只能識(shí)別字符串,如:
var mx = require('mxgraph');
這是因?yàn)椋瑆ebpack要判斷require引用的文件,并讀取和合并文件內(nèi)容。由于webpack無(wú)法執(zhí)行js代碼,所以,當(dāng)require的內(nèi)容是表達(dá)式時(shí),webpack無(wú)法正確獲取文件信息。
這屬于webpack無(wú)奈的bug,解決辦法是需要webpack具備執(zhí)行js代碼能力,比如可以?xún)?nèi)置一個(gè)javascript小引擎,以便解析表達(dá)式內(nèi)容。
在實(shí)際的編程中,如果遇到這種問(wèn)題,只需修改require中的表達(dá)式為字符串即可。
另外,當(dāng)進(jìn)行JS代碼混淆時(shí),也常會(huì)對(duì)require中的字符串內(nèi)容進(jìn)行加密,也會(huì)引發(fā)webpack的這個(gè)bug,解決辦法是:規(guī)避指定的字符,比如使用JShaman進(jìn)行JS代碼混淆時(shí),可以配置“保留字”,對(duì)指定的字符串不進(jìn)行加密。
特別聲明:以上內(nèi)容(如有圖片或視頻亦包括在內(nèi))為自媒體平臺(tái)“網(wǎng)易號(hào)”用戶(hù)上傳并發(fā)布,本平臺(tái)僅提供信息存儲(chǔ)服務(wù)。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.