Fix 'Cannot assign to read only property exports' in JS

By

Fix the TypeError: Cannot assign to read only property exports error from Webpack by switching from CommonJS module.exports to ES Modules export default.

~~~

This error means you are mixing two module systems in the same file: CommonJS (module.exports) and ES Modules (import/export). The fix is to pick one, and with Webpack that one should be ES Modules.

While working on a project, at some point I got this error:

TypeError: Cannot assign to read only property 'exports' of object '#<Object>' error

Why does this error happen?

The error is generated by Webpack, and it shows up when a file uses an import statement at the top, but then exports its values with module.exports at the bottom.

When the bundler sees an import, it treats the whole file as an ES module. In an ES module, the CommonJS exports object is read-only. So the moment your code assigns to module.exports, you get the TypeError at runtime.

The two syntaxes each work fine on their own. The problem is only having both in one file.

The fix

Instead of using the CommonJS syntax:

const calculateTotal = () => {}
module.exports = calculateTotal

use the ES Modules syntax:

const calculateTotal = () => {}
export default calculateTotal

Then you can import the exported function like this:

import calculateTotal from './calculateTotal'

You can also export multiple functions or objects from a file:

cart.js

const calculateTotal = () => {}
const applyDiscount = () => {}

export {
  calculateTotal,
  applyDiscount
}

Then you can import them as:

import { calculateTotal, applyDiscount } from './cart.js'

One thing to watch out for

After fixing the file the error pointed at, search the project for other files that mix the two systems. I had the same pattern copy-pasted in a couple of utility files, and the error came back as soon as one of them was imported.

A quick search for module.exports across your src folder finds them all. Convert each one to export default or named export, and the error is gone for good.

Tagged: JavaScript ยท All topics
~~~

Related posts about js: