Next.js构建项目遇Terser报错:import/export不能在模块代码外使用
解决Next.js构建时Terser报错:
'import' and 'export' cannot be used outside of module code 问题场景
构建Next.js项目时,Terser处理static/media/thread.4e53ce56.js文件时抛出语法错误,提示'import' and 'export' cannot be used outside of module code,最终导致webpack构建失败,报错详情如下:
x 'import', and 'export' cannot be used outside of module code ,-[1:1] 1 | import {Buffer} from 'node:buffer'; : ^^^^^^ 2 | import crypto from 'node:crypto'; 3 | import {parentPort} from 'node:worker_threads'; `---- Caused by: 0: failed to parse input file 1: Syntax Error Error: x 'import', and 'export' cannot be used outside of module code ,-[1:1] 1 | import {Buffer} from 'node:buffer'; : ^^^^^^ 2 | import crypto from 'node:crypto'; 3 | import {parentPort} from 'node:worker_threads'; `---- Caused by: 0: failed to parse input file 1: Syntax Error > Build failed because of webpack errors
解决方案
1. 修正文件存放路径
static/media目录用于存放图片、音频等静态媒体资源,而非JavaScript模块代码。如果thread.4e53ce56.js是业务代码或Worker线程脚本,将其移动到src目录或项目其他代码目录下,确保webpack能正确识别并处理它的ES模块语法。
2. 配置webpack处理Worker线程文件
从报错中的worker_threads依赖判断,该文件大概率是Worker线程脚本。Next.js默认webpack配置未适配这类文件,需手动添加配置:
- 安装依赖:
npm install worker-loader --save-dev - 在
next.config.js中添加webpack规则:module.exports = { webpack: (config) => { // 匹配你的Worker文件名规则,这里以thread.js为例 config.module.rules.push({ test: /thread\.js$/, use: { loader: 'worker-loader', options: { inline: 'fallback' } } }); return config; } };
3. 明确模块系统类型
- 如果项目使用CommonJS模块(
package.json中无"type": "module"),Node.js会默认将.js文件当作CommonJS模块,此时使用ES模块语法会报错。可以将该文件重命名为.mjs,强制标记为ES模块。 - 若要全局启用ES模块,在项目根目录的
package.json中添加:
注意:此修改会影响整个项目的模块导入导出语法,需确保所有代码都适配ES模块规范。"type": "module"
4. 调整Terser插件配置
强制Terser将目标文件识别为ES模块,在next.config.js中修改webpack的Terser配置:
module.exports = { webpack: (config) => { config.optimization.minimizer.forEach(minimizer => { if (minimizer.constructor.name === 'TerserPlugin') { minimizer.options.terserOptions = { ...minimizer.options.terserOptions, module: true, }; } }); return config; } };
内容的提问来源于stack exchange,提问作者Jaya sree
相关产品推荐
相关产品推荐

