【问题标题】:import and module.exports in Vuex module show Uncaught TypeError: Cannot assign to read only property 'exports' of objectVuex 模块中的 import 和 module.exports 显示 Uncaught TypeError: Cannot assign to read only property 'exports' of object
【发布时间】:2020-04-10 07:28:39
【问题描述】:

我有一个 Vue CLI 的 vuex 模块

import { Sev } from "../api";
const modules = {
  actions: {
    getData() {
      Sev();
    }
  }
};

module.exports = modules;

我在浏览器控制台中遇到错误

test.js?5df4:10 Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'
    at Module.eval (test.js?5df4:10)
    at eval (test.js:12)
    at Module../src/config/store_modules/test.js (app.js:1263)

然后我将代码更改为

import { Sev } from "../api";
// const modules = {
export default {
  actions: {
    getData() {
      Sev();
    }
  }
};
// module.exports = modules;

然后好好工作。但我不知道有什么不同。是bug吗?

【问题讨论】:

  • 取决于您的设置。为什么用 node.js 标记问题?你使用 Vue CLI 吗?你有具体的配置吗?该错误是由 Webpack 进行模块互操作的方式引起的。 module.exportsexport default 可以互换用于其他设置,但对于您的设置则不能。
  • 感谢您的评论,抱歉我标记错了我是新人我使用 Vue CLI 创建项目并且没有特定配置

标签: vue.js vuex-modules


【解决方案1】:

VueJS 是浏览器代码,使用 ES6 模块

import xxx from './path/to/xxx';
export xxx;
export default xxx;

而CommonJS是NodeJS使用的,完全不同

const yyy = require('./path/to/yyy');
module.exports = { yyy };
exports.zzz = yyy;

您正在编写 Vue 代码,因此您必须使用 ES6 模块和导入/导出语法,module 对象的行为与您在 ES6 中的预期不同

【讨论】:

  • 这不是真的。 module 对象存在是因为它是由捆绑程序创建的。您可以在错误消息中清楚地看到这一点。当 CommonJS 模块和 module.exports 在客户端应用程序中使用模块互操作正确处理时,有很多场景。 ES 模块应该与 Vue 一起使用是正确的,但 OP 已经知道了。
  • 是的,我知道;)我说“模块对象并不像您期望的那样存在”,但我的意思是“模块对象的行为与您期望的不一样”
猜你喜欢
  • 2016-02-22
  • 2021-05-03
  • 2017-04-24
  • 2022-08-18
  • 2013-01-15
  • 2018-06-30
  • 1970-01-01
  • 1970-01-01
  • 2019-02-12
相关资源
最近更新 更多