前言
最近一直在折騰 Nextjs15 ,也在斷斷續續地寫《Next.js15 實戰系列》的文章,后來總感覺文章如果沒有線上效果預覽差點意思,所以就想著先把目前做的項目先部署上線,后續再慢慢添加新功能。
因為之前沒有部署過 Nextjs15 工程項目,我就隱約感覺沒有那么簡單,果不其然,開發環境一切正常,打包構建時一堆報錯。
問題分析
控制臺報錯日志:
../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_root.js
profile:build: Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime
profile:build: Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation
profile:build:
profile:build: Import trace for requested module:
profile:build: ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_root.js
profile:build: ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isBuffer.js
profile:build: ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/lodash.js
profile:build: ./src/utils/Fetcher.ts
profile:build: ./src/@types/schema.ts
profile:build:
profile:build: ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/template.js
profile:build: Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime
profile:build: Used by default
profile:build: Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation
profile:build:
profile:build: Import trace for requested module:
profile:build: ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/template.js
profile:build: ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/lodash.js
profile:build: ./src/utils/Fetcher.ts
profile:build: ./src/@types/schema.ts
很明顯,這是由于工程中使用了 lodash-es 產生的報錯。
我就納悶了,開發環境使用 lodash-es 一切正常,能有什么報錯?
我跑到 Nextjs15 的 issues 尋找原因,發現真的有人有同樣的問題 - #51401,了解更多:Dynamic code evaluation is not available in Middleware
具體而言,不支持以下 api
:
- eval()
- new Function()
- WebAssembly.compile
- WebAssembly.instantiate
應該是 lodash-es 的源碼中包含了其中的 api
,導致打包報錯。
解決問題
一開始我按照官網和 #51401 的方案去嘗試解決問題
export const config = {runtime: "experimental-edge",unstable_allowDynamic: ["/src/utils/Fetcher.ts","/src/@types/schema.ts","*/`/node_modules/lodash-es/`",],matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};
但是不管我如何更改,折騰了一天,打包時這個報錯依然存在。
最后實在沒辦法,因為我使用 lodash-es 的 api
不多,最終刪除了 lodash-es,拷貝 radash 的部分源碼到本地,最后打包果然沒問題。
這個可能是最笨最無奈的辦法了,如果大家發現更好的解決方案,可以留言討論,哈哈
Github
:next-admin
線上預覽地址
:Next Admin