Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
There are several “read only property” errors you might encounter in JavaScript. Let’s cover the most common ones.
Attempted to assign to readonly property
This error occurs when you try to modify something that can’t be changed:
TypeError: Attempted to assign to readonly property
A common cause is trying to modify a string using dot notation. For example:
const data = '{"name": "test"}' // This is a string, not an object
data.name = 'Flavio' // Error! Strings are immutable
The fix is to parse the JSON first:
const data = '{"name": "test"}'
const obj = JSON.parse(data)
obj.name = 'Flavio' // Works!
Remember: Strings are immutable in JavaScript. Once defined, you can’t update individual characters or properties on them.
Cannot assign to read only property ‘exports’
This error is generated by Webpack:
TypeError: Cannot assign to read only property 'exports' of object '#<Object>' error
It means you’re mixing CommonJS and ES Module syntax incorrectly.
The problem
Using CommonJS syntax in an ES Modules context:
const myfunction = () => {}
module.exports = myfunction
The solution
Use ES Modules syntax instead:
const myfunction = () => {}
export default myfunction
Then import like this:
import myfunction from './myfunction'
Exporting multiple functions
To export multiple functions or objects:
// myfunctions.js
const myfunction1 = () => {}
const myfunction2 = () => {}
export {
myfunction1,
myfunction2
}
Import them as:
import { myfunction1, myfunction2 } from './myfunctions.js'
Other causes
This error can also occur when:
- Trying to modify a frozen object (
Object.freeze()) - Trying to modify a property defined with
writable: falsein a property descriptor - Using strict mode and trying to assign to a non-writable property