/

How to Fix the TypeError: Cannot Assign to Read Only Property 'exports' of Object '#' Error

How to Fix the TypeError: Cannot Assign to Read Only Property ‘exports’ of Object ‘#‘ Error

While working on a project, you might encounter the following error:

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

This error is typically generated by Webpack and indicates that you are attempting to use CommonJS syntax when you should be using ES modules.

Instead of using the CommonJS syntax:

1
2
const myfunction = () => {}
module.exports = myfunction

you should use the ES Modules syntax:

1
2
const myfunction = () => {}
export default myfunction

To import an exported function or object, you can use the following syntax:

1
import myfunction from './myfunction'

If you want to export multiple functions or objects from a file, you can do so as follows:

myfunctions.js

1
2
3
4
5
6
7
const myfunction1 = () => {}
const myfunction1 = () => {}

export {
myfunction1,
myfunction2
}

To import these multiple exports, you can use the following syntax:

1
import { myfunction1, myfunction2 } from './myfunctions.js'

tags: [“webpack”, “commonjs”, “es-modules”]

How to Fix the TypeError: Cannot Assign to Read Only Property 'exports' of Object '#' Error