使用create-react-app脚手架搭建了一个react项目,在项目中拷贝了其他项目中的一些组件代码,在编译时报如下错误:
Cannot assign to read only property 'exports' of object '#<Object>'
google以下两个地方找到了答案:
github的issue:https://github.com/webpack/webpack/issues/4039
stackoverflow:https://stackoverflow.com/questions/52395149/babel-7-upgrading-creating-error-typeerror-cannot-assign-to-read-only-propert
首先,我们了解下问题的原因:
react通过Webpack ,支持 ES6 modules,虽然你仍然可以使用 require() 和 module.exports ,但强烈建议你使用 import 和 export。这里我们可以看到require和module.exports是一对模块化api,import和export是一对模块api,如果在项目中,一个文件中同时使用了上面的两种方式来引入、暴漏模块,那么就会报上面的错误。
即:Try not to mix require / module.exports
and import / export
, ensure to be consistent with one.
接下来,解决方法:
在当前js文件中,讲其中一种api用法改成另外一种即可。