/

如何修復 TypeError: Cannot assign to read only property 'exports' of object '# ' 錯誤

如何修復 TypeError: Cannot assign to read only property ‘exports’ of object ‘# ‘ 錯誤

在進行項目開發時,有時會遇到以下錯誤:

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

該錯誤是由 Webpack 生成的,它表示您試圖在需要使用 ES 模塊 的地方使用了 CommonJS

請避免使用 CommonJS 語法:

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

改用 ES 模塊語法:

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

然後,您可以像這樣導入導出的函數或對象:

1
import myfunction from './myfunction'

您也可以從文件中導出多個函數或對象:

1
2
3
4
5
6
7
8
9
myfunctions.js

const myfunction1 = () => {}
const myfunction1 = () => {}

export {
myfunction1,
myfunction2
}

然後,您可以像這樣導入它們:

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

tags: [“CommonJS”, “ES modules”, “Webpack”]

如何修復 TypeError: Cannot assign to read only property 'exports' of object '# ' 錯誤