uniapp referenceerror: exports is not defined 如何解决

在uniapp开发中遇到报错"ReferenceError: exports is not defined",这个错误通常出现在编译或运行阶段。请问这是什么原因导致的?应该如何解决?我已经检查了代码中exports的使用方式,但不确定是否与uniapp的模块化规范冲突。有没有遇到类似问题的朋友能分享下解决方案?

2 回复

manifest.json中设置"module": "commonjs",或使用@babel/plugin-transform-modules-commonjs插件。


在 UniApp 中遇到 ReferenceError: exports is not defined 错误,通常是由于 模块化语法 在非 Node.js 环境(如小程序)中不被支持导致的。以下是常见原因和解决方案:


1. 原因分析

  • CommonJS 语法问题:UniApp 编译到小程序时,不支持 exportsmodule.exportsrequire 等 Node.js 模块语法。
  • 第三方库兼容性:某些 npm 包未适配小程序环境,直接引入了 CommonJS/ES6 模块。

2. 解决方案

方案一:修改模块导入方式(推荐)

将 CommonJS 语法改为 ES6 模块化语法

// ❌ 错误写法(CommonJS)
const utils = require('./utils.js');
module.exports = { ... };

// ✅ 正确写法(ES6)
import utils from './utils.js';
export default { ... };

方案二:配置 transpileDependencies

vue.config.js 中配置需要转译的依赖:

module.exports = {
  transpileDependencies: ['your-library-name'], // 替换为实际库名
};

方案三:使用 @babel/plugin-transform-modules-commonjs

安装并配置 Babel 插件:

npm install --save-dev [@babel](/user/babel)/plugin-transform-modules-commonjs

babel.config.js 中添加:

module.exports = {
  plugins: ['[@babel](/user/babel)/plugin-transform-modules-commonjs'],
};

方案四:检查第三方库

若问题由第三方库引起:

  1. 寻找替代库(明确支持小程序)。
  2. 通过 条件编译 仅在小程序端使用兼容版本:
// #ifdef MP-WEIXIN
import library from 'weixin-compatible-library';
// #endif

3. 排查步骤

  1. 检查代码中是否直接使用 exportsrequire
  2. 运行 npm run dev:mp-weixin 观察编译警告。
  3. 微信开发者工具 中开启 ES6 转 ES5(项目设置 → 本地设置)。

总结

优先使用 ES6 模块化语法,并通过 transpileDependencies 处理第三方库兼容性。确保开发环境配置正确,通常可解决此问题。

回到顶部