webpack: Cannot assign to read only property 'exports' of object '#
Do you want to request a feature or report a bug? bug
What is the current behavior? Module with code
// 'a.js'
module.exports = { a: 'b' };
// b.js
const a = require('./a.js').a;
export default {
aa: a
}
Gives error:
Cannot assign to read only property 'exports' of object '#<Object>'
Appeared after upgrade webpack 2.2.0.rc.6 -> 2.2.0.
If ‘harmony-module’ is ES2015 module, then looks like it’s now impossible to mix require
and export default
in single module. If it so, that’s okay, but should be mentioned in docs.
Please mention other relevant information such as the browser version, Node.js version, webpack version and Operating System. MacOS 10.12.2 node.js 6.9.2 webpack 2.2
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Reactions: 121
- Comments: 113 (21 by maintainers)
Commits related to this issue
- bug(template): tree-shaking option has problem. it removed. see also https://github.com/webpack/webpack/issues/4039 — committed to naver/generator-egjs by deleted user 7 years ago
- UI: Uplift outdated packages. Webpack is now official version! ES2015 modules is now transpiled to commonjs. This is a work-around/solution for https://github.com/webpack/webpack/issues/4039 since we... — committed to Combitech/codefarm by christensson 7 years ago
- Reverting modules change due to webpack issue: https://github.com/webpack/webpack/issues/4039 — committed to EricMCornelius/ease by EricMCornelius 7 years ago
- Don't mix import with module.exports Workaround for https://github.com/webpack/webpack/issues/4039 — committed to mapbox/mapbox-gl-directions by anandthakker 7 years ago
- 在webpack下混用import和module.exports会导致错误 在webpack下混用import和module.exports会导致错误Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>' 这个错误在webpack的issues里有提及 https://git... — committed to abeet/element-react by abeet 7 years ago
- 在webpack下混用import和module.exports会导致错误 在webpack下混用import和module.exports会导致错误Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>' 这个错误在webpack的issues里有提及 https://git... — committed to abeet/element-react by abeet 7 years ago
- Replace module.exports as webpack complains about it https://github.com/webpack/webpack/issues/4039 — committed to nathancyam/anime-app-frontend by nathancyam 7 years ago
- Fix mix of import and module.exports Build with webpack will raise `Cannot assign to read only property 'exports' of object '#<Object>' (mix require and export)`, see https://github.com/webpack/webpa... — committed to cpunion/react-native-elements by cpunion 7 years ago
- refactor: Add default import Removes module.exports line which was raising the error described here: https://github.com/webpack/webpack/issues/4039 — committed to Kitware/candela by jeffbaumes 7 years ago
- Fix can't assign readonly property of module.exports via https://github.com/webpack/webpack/issues/4039 instead of using `export default` — committed to limodou/vuecoms by limodou 7 years ago
- Dont Mix `import` and `module.exports` statements See https://github.com/webpack/webpack/issues/4039 — committed to casesandberg/react-native-swiper by casesandberg 7 years ago
- fix webpack error https://github.com/webpack/webpack/issues/4039 no idea why this code snippet causes webpack to think this module is using `import`, but hey [we can work around it][1] [1]: https:/... — committed to root-systems/cobuy by ahdinosaur 7 years ago
- update to es2015 syntax to work around webpack2 issue https://github.com/webpack/webpack/issues/4039 — committed to Shuliyey/instascan by deleted user 7 years ago
- transform-inline-environment-variables moved environment specific babel plugins transform-inline-environment-variables moved environment specific babel plugins to try to fix issue with mixing import ... — committed to prescottprue/redux-firestore by prescottprue 7 years ago
- Converted to ES6 to prevent issue with webpack https://github.com/webpack/webpack/issues/4039#issuecomment-273979302 — committed to QuantumBA/walk-object by piranna 6 years ago
- Use @babel/polyfill instead of @babel/transform-runtime in order to load iroha-util.js as is. According to the comment below, transform-runtime adds `import` to each file and makes it unable to use `... — committed to soramitsu/iroha-wallet-js by oimou 6 years ago
- 🐛 fix bugs about module.exports (Babel), see https://github.com/webpack/webpack/issues/4039 — committed to Airyworks/scarlet by Illyrix 6 years ago
- babel-loader will error webpack/webpack#4039 !! WTF — committed to eyasliu/electron-startkit by eyasliu 6 years ago
- CF-684: Fixed i18n not working due to https://github.com/webpack/webpack/issues/4039 — committed to ProjectSpectero/app by deleted user 6 years ago
- fix($core): Cannot assign to read only property 'exports' of object (close: #869) This is weird issue of webpack. since ClientComputedMixin was used both in server and client side, client es module w... — committed to vuejs/vuepress by ulivz 6 years ago
The code above is ok. You can mix
require
andexport
. You can’t miximport
andmodule.exports
.Now that Babel 7.x is out, I’ll just say that this should essentially be resolved. The only time you should see this, with Babel 7.x, is if you’re doing one of:
import
andmodule.exports
in the same file, which is not allowed by Webpack. You can sidestep this by setting"modules": "commonjs"
, which will make Babel compile theimport
to arequire
. This breaks tree shaking, as mentioned above though, so fixing your code would be a better idea.useBultins: 'entry'/'usage
, or@babel/plugin-transform-runtime
, and you are running Babel on CommonJS files (either your own, or in randomnode_modules
, if you’re trying to compile that). Babel assumes files are ES modules by default, meaning those transforms would insertimport
statements into your file, triggering case1.
above. You can avoid this issue by settingsourceType: "unambiguous"
in your Babel configuration, which will tell it to guess the type, like Webpack does, instead of assuming all files are modules.@Zdend You could be hitting either or both of these cases, it is hard to say.
This issue was newly affecting me after instructing Babel to not transpile module syntax. As sokra described, it only occurred when trying to use CommonJS style
module.exports
inside of ES modules.require
always works. This can be fixed by simply replacing allmodule.exports = ...
toexport default ...
where applicable, as this is seemingly equivalent for old Babel-style ES module transpilation. (Note though, that importing this module usingrequire
will probably give you an option with adefault
key rather than the default export itself, so it’s probably best you make the switch across the entire codebase at once.)M
transform-runtime
addsimport
to your files…The way I see it, there are a few good solutions:
transform-runtime
support outputtingrequire
statements instead ofimport
statements, as an option. This seems unlikely, because it looks like Babel is already relying on the fact thatimport
is declarative.transform-es2015-modules-commonjs
. This would replace allimport
statements withrequire
statements. If you are not using anyimport
/export
syntax in your app, this solution is probably ideal, because it incurs no extra cost. However, if you are using ES modules, then this will likely impact Webpack 2’s ability to perform tree shaking. (I’m sure everyone is aware of this.)require
does not have to be globally replaced, onlymodule.exports
andexports
statements.Taking a quick glance, this is definitely the culprit:
https://github.com/webpack/webpack/commit/a7a41848c73f14ff294b48285f42063e1f0de4b1
As it says,
module.exports
is read-only in ES modules. If you’re gettingmodule.exports
as read-only in a CommonJS module, THAT would be a bug, but that file is very much not a CommonJS file if it contains anyexport
/import
statements. I can confirm that this was the problem in my case and it was fixed by making my ES modules properly use ES exports. As a noterequire
still works just fine inside of any module.From my PoV it seems like Webpack’s new behavior ultimately makes a lot more sense than the old behavior. It is fairly inane to allow mixing of
import
statements and CommonJSmodule.exports
, and probably was never intended to work that way.I solved the problem by adding “@babel/plugin-transform-modules-commonjs”
I actually just got this to work by changing my
.babelrc
file.The big change that worked for me was removing
modules: false
fromes2015
before:
"presets": [ [ "env", { "modules": false, }
after:"presets": [ [ "env", { "modules": "commonjs", }
it seems to be .babelrc’s modules does’t match commonjs. here is the :https://www.babeljs.cn/docs/babel-preset-env docsUsing babel 7 with webpack v4 this solved mine:
plugins: [ [‘@babel/plugin-transform-modules-commonjs’, { ‘allowTopLevelThis’: true }] ]
Maybe add this info to migration guide?
was suddenly having this issue on a vue-cli project after trying out the 4.0.alpha.1
adding
sourceType: 'unambiguous',
to my babel.config.js file made the error go awayAdding
sourceType: 'unambiguous'
, to my babel.config.js fixed things for me.I wouldn’t normally comment like this, but this issue was one of the first links I opened from google and I missed the solution: https://github.com/webpack/webpack/issues/4039#issuecomment-419284940. (way up over a year ago)
I think for me what happened was that i am using
@babel/preset-env
with the option:useBuiltIns: 'usage'
This feature lets babel automatically import polyfills for stuff based on the provided targets when they are used in the file.So
preset-env
would automatically import polyfills from core js inside my commonJS modules. for example this file:So the
import
automatically inserted at the top of my file and the module exports didn’t play along well i guess… I hope i’m right 🤷♂️Fixed mine by removing { “modules”: false } from this line in .babelrc: [“env”, { “modules”: false }]
@sokra how difficult would it be to add a webpack compile error for this case? Seems there’s room for a clearer explanation
I solved the problem by adding
modules: "cjs"
topreset-env
npm install webpack@2.1.0-beta.27 --save
can release the pain temporarily.This is the reason: https://github.com/webpack/webpack/pull/3958 But I like this suggestion: https://github.com/webpack/webpack/issues/3917#issuecomment-272746700
the better error info should be “module.exports is readonly when using ES2015 modules. Do not mix import with module.exports.”
@johnwchadwick I just upgraded one of my project to Webpack 2.2.x and it fixed my issue. Thank you.
Replaced
module.exports
withexport default
, and therequire(...)
withrequire(...).default
I solved this issue by adding
"sourceType": "unambiguous"
in my babelrc fileAfter adding it,
@babel/plugin-transform-runtme
will injectrequire
expression instead ofimport
in my commonjs files so they won’t mix XDHad this issue today, adding this in
.babelrc
fixed it (https://github.com/webpack/webpack/issues/4039#issuecomment-419284940):Removing
"modules: false"
in .babelrc might workI’ve written the rule and it works. I think it’d be best to add to
eslint-plugin-import
so I’ve added an issue there: https://github.com/benmosher/eslint-plugin-import/issues/760Unfortunately the exports-loader injects module.exports statements so using it with a legacy codebase and injecting that to a es6 project has become impossible.
I can only speak for myself, but for the situation affecting me the module within which
module.exports
is read-only does not have anyimport
orexport
statements. It appears that the heuristic that is identifying the file in question as a ‘harmony’ model is misfiring in some situations.I was also using
useBuiltIns: "usage"
and didn’t want to go back tocore-js@2
and for some reasonsourceType: "unambiguous"
only moved the error OP (and I) had to the following error:occurring in most Webpack loaders during build.
After looking and searching for some time I stumbled over the following posts:
Honestly, I don’t understand what is going on here. But excluding core-js from Babel (as shown in the StackOverflow post) in conjunction with setting
sourceType: "unambiguous"
solved the issues I had withcore-js@3
.I’d love if someone could explain the why and what, I cannot. But hopefully this helps the next guy stumbling over this issue.
I had the following
.babelrc
And was able to fix this by removing the
add-module-exports
plugin. TBH, I can’t even recall why I had it in there to begin with… but upon removal it started working as expected. Nobody else has mentionedadd-module-exports
yet so I thought I’d chime in too to point out that it’s not justtransform-runtime
causing this.@sokra here are the relevant config files:
.babelrc:
webpack.config.js (simplified):
webpack@3.4.1
This will work:
a.js
b.js
But this will not work:
a.js
b.js
This will work:
a.js
b.js
output
But this will cause a warning:
a.js
b.js
output
So
I think the keyword
typeof
will cause the ES/CommonJS module type distinguishing error.I find myself also being bitten by this issue since upgrading to
2.2.0
. In my case, my hypothesis is a require chain that looks like:I’m sorry that I can’t provide any more details at this time.
@Zdend Note that you’ll miss out on tree shaking by doing that.
Just bumped into this myself. There should probably be an eslint rule that disallows using
import
in a file withmodule.exports
. Anyone know whether this exists? If not, I’ll make it 😃I’m not at all familiar with the internals but a quick, manual binary search suggests the regression is here: https://github.com/webpack/webpack/compare/v2.2.0-rc.4...v2.2.0-rc.5
Attn: @sokra, @TheLarkInn I think this issue should be re-opened.
This worked for me as well, do you understand why though? I am so perplexed
I fixed this by removing module:false from .babelrc
Before
After
this answer worked for me, thanks a lot
I was also running into this problem when using
@babel/preset-env
with theuseBuiltIns: 'usage'
option, switching tocore-js
version 2 is what fixed it for me.The common causes of this issue are spelled out in https://github.com/webpack/webpack/issues/4039#issuecomment-419284940
While force-loading
@babel/plugin-transform-modules-commonjs
technically works, it is not what I would recommend since it essentially disables many of the benefits Webpack can provide with tree shaking.This configuration works for me.
Good afternoon,
I am using Vue 2.5.16 and running into a similar problem. After reading through this thread my issue still perplexes me to why my console is throwing this error
Cannot assign to read only property 'exports' of object '#<Object>'
I am bringing in this helper function using
const helper = require("../assets/helper/helper.js");
while using;module.exports=simpleNoise: function(){this.perm = new Uint8Array(512);}
I have a larger function that I wish to export into my template, but I have isolated this line to be causing the error. The instantiation of a
new Uint8Array()
throw the error.Any guidance on why this might be would be greatly appreciated.
It’s clear that this issue happens when
import
andmodule.exports
are mixed. As well it’s clear that the possible solution, such as removingmodules:false
from the['es2015', {modules: false}]
equasion is not good, as it affects tree shaking.Have two questions though:
require
my module on the front-end side (explicitly) this would solve the issue. Asmodule.exports
module would berequired
. But I see the same error. Why?whily
react
leads to:And
workflow
leads to:In the console I see the error about the workflow inclusion:
how the
react
case is different? 3. What is the expected way to have an isomorphic modules and use it both onnodejs
andfront-end
parts. (I don’t want to transpile my nodejs code)@sokra
Regards,
你把module.export改为export.default试试
https://babeljs.io/docs/en/options#sourcetype
Given that the default for
sourcetype
is “module”, I wonder why Babel doesn’t treat the presence ofmodule.exports
(and the absence of import/export statements) as a signal that the file should be parsed as “script” instead, to avoid throwing this error.Just a remind, see https://github.com/webpack/webpack/issues/4039#issuecomment-419284940 to fix this problem
If you don’t want to use babel, my solution works.
I fixed this by making an entry point file like.
node index.js
and any file I imported inside
app.js
and beyond worked withimports/exports
I have been struggling to find solution for the last 4 hours, this worked for me thank you!!!
@pfeiferbit That sounds like it would be a compilation issue unrelated to the issues here. Most likely, if you’re using one of the
core-js
import-injection plugins, and compilingcore-js
itself, you’ll be injectingcore-js
imports intocore-js
itself, creating dependency cycles and errors like that one. You shouldn’t run Babel oncore-js
so excluding it is the way to go. See https://github.com/babel/babel/issues/8754@STRsplit Ok, my bad 😃 Hopefully it will help some others though! Can’t help you with
babel.config.js
.Yeah that error means you did
instead of
Note the extra set of square brackets.
Thanks @loganfsmyth
Short answer。
If you are using babel 7 and
bable-trunsform-runtime
like me, you can set:@bitcot I guessed, I tried, it worked, no explanation…
Faced this issue when
import
ed.js
with ES6class
andmodule.exports =
into myvue-cli
project. Webpack config:babel config:
Included class:
@PavelPolyakov you should post a reproduction of your issue instead of snippets. It will make it a lot easier for others to follow and diagnose the issue.
Then the codes not truly isomorphic, because you’re not using the same output on both platforms. You can’t have it both ways 😃
If so this particular feature looks not very thought through. I think there should be a way for the developer to have an isomorphic modules for nodejs and webpack. This is very natural need.
what is the recommended solution for this issue when a dependent npm module is performing an import when they shouldn’t? Is there any way to have webpack automatically alter the
import blah from 'blah'
tovar blah = require('blah').default
?@kentcdodds PR not really an option as the module devs are trying to decide on which style to adopt, 1.5 months ago, can’t force someone else to accept a PR to resolve a bundling issue.
Make a pull request to that module?
@TheLarkInn Definitely something we can explore for
7.0
. There are several issues around transform-runtime that have been longstanding that we’re hoping to fix.@ggoodman are you using babel-runtime?
@sokra probably in real code I had something more, that caused the issue. Now I’ve refactored this part to
import export
and it works fine.I’ll try check it in more clear example. For now I believe the issue can be closed.