Next.js生产构建因外部npm包触发Terser错误失败
Next.js构建失败:Terser解析cubing.js模块报错问题
执行Next.js项目生产构建命令next build时失败,原因是Terser无法解析外部npm包cubing.js中的JavaScript文件。但根据Next.js文档,默认应使用SWC而非Babel或Terser进行JS转换与压缩,对此存在疑惑。
错误信息
Failed to compile. static/media/search-worker-entry.3cb2cae1.js from Terser x 'import', and 'export' cannot be used outside of module code ,-[1:1] 1 | import { : ^^^^^^ 2 | nodeEndpointPort 3 | } from "./chunk-NEAVVKH5.js"; 4 | import { `---- Caused by: 0: failed to parse input file 1: Syntax Error
引发错误的NPM包文件
问题文件属于cubing npm包,路径为node_modules/cubing/dist/lib/cubing/chunks/search-worker-entry.js,代码内容如下:
import { nodeEndpointPort } from "./chunk-NEAVVKH5.js"; import { exposeAPI } from "./chunk-7GUL3OBQ.js"; import "./chunk-VL22SFND.js"; // src/cubing/search/worker-workarounds/search-worker-entry.js if (exposeAPI.expose) { (async () => { await import("./inside-KOB7JHHP.js"); const messagePort = globalThis.postMessage ? globalThis : await nodeEndpointPort(); messagePort.postMessage("comlink-exposed"); })(); } var WORKER_ENTRY_FILE_URL = import.meta.url; export { WORKER_ENTRY_FILE_URL }; //# sourceMappingURL=search-worker-entry.js.map
项目配置
package.json
{ "dependencies": { "react": "^18", "react-dom": "^18", "next": "14.1.4", "react-router-dom": "^6.22.2", "react-scripts": "5.0.1", "web-vitals": "^2.1.4" ... }, "devDependencies": { "typescript": "^5.3.3", "@babel/plugin-proposal-private-property-in-object": "^7.16.7", "@types/node": "^20", "@types/react": "^18", "@types/react-dom": "^18", ... }, "overrides": { "typescript": "^5.3.3" } }
tsconfig.json
{ "compilerOptions": { "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "plugins": [ { "name": "next" } ], "paths": { "@/*": ["./src/*"] } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "exclude": ["node_modules"] }
Next.js文档说明
The Next.js Compiler, written in Rust using SWC, allows Next.js to transform and minify your JavaScript code for production. This replaces Babel for individual files and Terser for minifying output bundles.
疑问与求助
- 为什么Terser会参与本次构建过程?
- 应采取哪些步骤解决此问题,完成项目编译?
环境信息
- npm版本:10.2.4
- Node.js版本:v21.6.0
- Next.js版本:14.1.4
内容的提问来源于stack exchange,提问作者T. Grumser
相关产品推荐
相关产品推荐

