React Cannot Assign to Read Only Property
The code above is ok. You can mix crave and export. You can't mix import and module.exports.
@sokra probably in real code I had something more, that caused the issue. Now I've refactored this part to import consign and it works fine.
I'll endeavor check information technology in more clear example. For now I believe the issue can exist closed.
This issue was newly affecting me after instructing Babel to not transpile module syntax. As sokra described, it merely occurred when trying to use CommonJS mode module.exports inside of ES modules. require e'er works. This tin exist fixed past simply replacing all module.exports = ... to export default ... where applicable, as this is seemingly equivalent for former Babel-style ES module transpilation. (Note though, that importing this module using require will probably give you an pick with a default key rather than the default export itself, so it'south probably all-time you make the switch across the entire codebase at once.)
I find myself also beingness bitten by this issue since upgrading to 2.two.0. In my case, my hypothesis is a crave concatenation that looks like:
CommonJSModule --requires--> ESModule --requires--> AnotherCommonJSModule I'k sorry that I can't provide any more details at this time.
Taking a quick glance, this is definitely the culprit:
https://github.com/webpack/webpack/commit/a7a41848c73f14ff294b48285f42063e1f0de4b1
find harmony modules before parsing exports is at present undefined in ESM module.exports is at present read-only in ESM and returns undefined ascertain is now undefined in ESM Every bit information technology says, module.exports is read-only in ES modules. If you lot're getting module.exports as read-but in a CommonJS module, THAT would be a bug, but that file is very much not a CommonJS file if information technology contains any export/import statements. I can confirm that this was the problem in my case and information technology was fixed past making my ES modules properly use ES exports. As a note crave yet works just fine within of any module.
From my PoV it seems like Webpack's new behavior ultimately makes a lot more than sense than the old behavior. It is fairly inane to allow mixing of import statements and CommonJS module.exports, and probably was never intended to work that way.
Maybe add this info to migration guide?
I can just speak for myself, but for the situation affecting me the module within which module.exports is read-merely does not have any import or consign statements. It appears that the heuristic that is identifying the file in question as a 'harmony' model is misfiring in some situations.
@ggoodman are you using boom-boom-runtime?
@sokra hither are the relevant config files:
.babelrc:
{ "presets": [ ["env", { "modules": false, "targets": { "browsers": ["final two versions", "safari >= 7"] } }] ], "plugins": ["transform-runtime", "syntax-dynamic-import"] } webpack.config.js (simplified):
'employ strict'; const ExtractTextPlugin = require('extract-text-webpack-plugin'); const Path = require('path'); const Webpack = require('webpack'); const config = { cache: true, devtool: process.env.NODE_ENV !== 'production' ? 'source-map' : false, context: Path.join(__dirname), output: { path: Path.bring together(__dirname, 'build'), filename: '[proper name].js', chunkFilename: '[name].js', publicPath: '/static/', }, recordsPath: Path.join(__dirname, 'recordsCache'), module: { rules: [{ test: /\js$/, exclude: /node_modules/, utilise: [ { loader: 'ng-annotate-loader', }, { loader: 'boom-boom-loader', options: { cacheDirectory: true, }, }, { loader: 'string-replace-loader', options: { multiple: [ { search: /API_URL/g, supplant: process.env['PLUNKER_API_URL'] }, { search: /EMBED_URL/g, supervene upon: procedure.env['PLUNKER_EMBED_URL'] }, { search: /RUN_URL/g, replace: process.env['PLUNKER_RUN_URL'] }, { search: /SHOT_URL/g, supercede: procedure.env['PLUNKER_SHOT_URL'] }, { search: /WWW_URL/g, replace: process.env['PLUNKER_WWW_URL'] }, ], }, }, ] }, ], }, plugins: [ new ExtractTextPlugin({ filename: '[name].css', disable: simulated, allChunks: true, }), ], resolve: { modules: [ Path.join(__dirname, 'node_modules'), Path.join(__dirname, 'src'), ], }, }; module.exports = config; Chiming in as I'thousand getting this error in the browser as well, but neither the requiring module, nor the required module accept any import or export statements in them. I am using transform-runtime if that'south relevant.
transform-runtime adds import to your files...
@sokra I was non aware that this plugin would add import to my files.
If removing that plugin is a solution, what alternative can we consider and so that we don't have babel-runtime stuff like _classCallCheck included for every source file using ES6 features like coursees?
The way I see it, at that place are a few skillful solutions:
- Brand
transform-runtimesupport outputtingrequirestatements instead ofimportstatements, as an choice. This seems unlikely, because it looks like Babel is already relying on the fact thatimportis declarative. - Use
transform-es2015-modules-commonjs. This would supersede allimportstatements withcravestatements. If you are not using anyimport/exportsyntax in your app, this solution is probably ideal, because it incurs no extra cost. However, if yous are using ES modules, then this will likely touch on Webpack 2's power to perform tree shaking. (I'm sure everyone is aware of this.) - Utilize ES modules beyond the board. I think this is the most correct affair to do. Is there a reason why existing CommonJS exports can't simply be migrated?
requiredoes not have to be globally replaced, justmodule.exportsandexportsstatements.
How i can reproduce module.exports behavior?
I had entry point with name LoginPage, i need to build library with the same proper name, after that i init it on the page using new LoginPage();
Now i should use new LoginPage.LoginPage() or new LoginPage.default();
How i can resolve this event?
adding import (by transform-runtime) also means that the file is switched into strict mode, which could break you code. In my opinion transform-runtime should be changed.
I had the post-obit .babelrc
{ "presets": [ [ "es2015", { "modules": false } ], "phase-0", "react" ], "plugins": [ "add together-module-exports", "transform-class-backdrop", "transform-object-rest-spread", "transform-object-assign" ] } And was able to fix this by removing the add-module-exports plugin. TBH, I can't even call back why I had information technology in there to begin with... simply upon removal it started working every bit expected. Nobody else has mentioned add-module-exports yet so I thought I'd chinkle in too to indicate out that it's not just transform-runtime causing this.
I am having the same problem with vis projection. I made the well-nigh simple example if somebody have any idea what could be the problem. Mistake is in vis code. https://github.com/almende/vis
It does not seam like related to any plugin or mixing of import and module.exports.
error:
Uncaught TypeError: Cannot assign to read merely holding 'exports' of object '#<Object>' at Object.eval (ItemSet.js:2296) at eval (ItemSet.js:2298) at Object.../node_modules/vis/lib/timeline/component/ItemSet.js instance:
https://github.com/primozs/vis-example-webpack2
I had no problems in versions:
"webpack": "2.1.0-beta.27", "webpack-dev-server": "v2.1.0-beta.12", @johnwchadwick I just upgraded one of my project to Webpack 2.two.x and it stock-still my upshot. Give thanks y'all.
Replaced module.exports with consign default, and the require(...) with crave(...).default
Unfortunately the exports-loader injects module.exports statements then using information technology with a legacy codebase and injecting that to a es6 project has become incommunicable.
Is at that place any progress on this? I am unable to import a legacy library. Unfortunately i am unable to use import / export in legacy library.
@hzoo Hey is there a way to let transform-runtime apply crave instead important's
I really just got this to work by irresolute my .babelrc file.
{ "presets": [ "es2015", "es2016", "stage-2" ], "plugins": [ "transform-async-to-generator", "transform-class-properties", "transform-object-balance-spread", "transform-export-extensions", "transform-runtime", "lodash" ] } The big change that worked for me was removing modules: false from es2015
@TheLarkInn Definitely something we tin can explore for 7.0. At that place are several issues effectually transform-runtime that have been longstanding that we're hoping to set up.
@loganfsmyth Awesome merely wanted to followup. Should we track this or you lot all? Doing some event purging this week lol.
Just bumped into this myself. There should probably exist an eslint rule that disallows using import in a file with module.exports. Anyone know whether this exists? If not, I'll brand it :)
你把module.export改为export.default试试
@smitt04 :
The big alter that worked for me was removing modules: false from es2015 👍 two
This will break tree shaking.
Better approach would be to supersede module.exports with exports default. Volition that piece of work for you?
@abhinavsingi unfortunately I tin can't employ exports default. I employ that in all my own new code. But the trouble was when I imported a node module that was using module.exports
Correct now, i don't call back it is right to employ import / export on node js modules, until node supports them natively. Client side lawmaking is ok to transpile since we can't write a lot of es6+ in browsers and usually yous have a build / minify stage on deployment. But having to transpile your lawmaking to run on node i think is an extra step that doesn't need to exist done. At present i have to compile / transpile my lawmaking be fore testing.
what is the recommended solution for this issue when a dependent npm module is performing an import when they shouldn't? Is at that place any mode to take webpack automatically alter the import blah from 'blah' to var blah = crave('blah').default ?
@kentcdodds PR non really an option as the module devs are trying to decide on which mode to adopt, 1.v months ago, can't force someone else to accept a PR to resolve a bundling outcome.
@patsissons, I can capeesh that. Forking is e'er an selection. Y'all could also write a custom loader for that module I guess... Though there'south probably an easier way...
I submitted a PR none the less, https://github.com/almende/vis/pull/3063
This outcome just means I accept to bundle the entire library, which means my bundle is a bit larger than it needs to be. Not critical, just annoying :)
Why would webpack2 banned such a rule???? It can certainly cause a lot of trouble! Every module has to be rewrite
I had this trouble when I had ane file with mix of consign default and require('...'). I'k ok with changing it, but is information technology possible to raise an exception on webpack build step?
Guys, would be cool to add link to current issue into mistake on mixed import and module.exports
Is it possible and reasonable?
Guys, would be cool to add link to current consequence into error on mixed import and module.exports
Is information technology possible and reasonable?
I would have a PR for that @a-x- feel free and tag me when you create it.
It'due south clear that this result happens when import and module.exports are mixed.
As well it'south articulate that the possible solution, such as removing modules:false from the ['es2015', {modules: false}] equasion is non practiced, as information technology affects tree shaking.
Take 2 questions though:
- I thought that if I volition
cravemy module on the forepart-end side (explicitly) this would solve the consequence. Asmodule.exportsmodule would berequired. But I encounter the same fault. Why? - Why I don't run across such error for `React, for case. In my code, as the same file I take:
import React, {Component} from 'react'; import Workflow from 'common/modules/workflow'; whily react leads to:
And workflow leads to:
In the console I run into the error most the workflow inclusion:
how the react case is dissimilar?
- What is the expected manner to take an isomorphic modules and use it both on
nodejsandfront end-stopparts. (I don't want to transpile my nodejs code)
@sokra
Regards,
You lot have to transpile your node code since node doesn't support import/export.
@ljharb
thanks for the reply.
why I don't accept the same outcome while importing the react ?
I assume because Workflow is using export syntax, and React, as a published library, is using module.exports. Non really certain tho.
If so this item feature looks not very thought through. I think in that location should exist a style for the programmer to accept an isomorphic modules for nodejs and webpack. This is very natural demand.
The simply way to practise that is to always transpile everything using boom-boom and webpack.
@ljharb
but that's the matter :) I don't want to transpile everything. nodejs has enough ES2015 features to non be transpiled. even async/wait. so it feels correct to run the original lawmaking.
And then the codes non truly isomorphic, because you're non using the same output on both platforms. Y'all tin't have it both ways :-)
How-do-you-do @sokra ,
I know you lot're busy.
Merely the question from https://github.com/webpack/webpack/problems/4039#issuecomment-309746398 , why I can import from 'react' merely can not import my custom module, while they both do module.exports - doesn't allow me to sleep :)
Please, consider pointing me to the right direction.
Thanks in advance.
Regards,
@PavelPolyakov looks like you utilise module.exports = Workflow, but somewhere above your're exporting dependencies using export, instead of require. Tin can you lot make sure that you don't have import or export statements in your Workflow.js?
hi @KELiON, thanks for trying to help.
No, there are no imports above.
The modules configuration, every bit it is stated above is important too:
presets: [['es2015', {modules: faux}], 'react'], Whenever I annotate it out information technology works, whether I use imports or require.
@KELiON , @ljharb
I believe I institute the issue why it works for the node_modules, but non for the regular modules.
And the issue was - that node_modules are excluded from the boom-boom-loader.
Probably, when boom-boom-loader meets module.exports something goes incorrect.
@PavelPolyakov you should mail a reproduction of your issue instead of snippets. Information technology volition brand it a lot easier for others to follow and diagnose the consequence.
[email protected]
This will work:
a.js
module.exports = {}; b.js
import a from './a' console.log(a) Only this will not work:
a.js
// the occurrence of keyword `typeof` will lead to error: // `Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'` var x = typeof 1; module.exports = {}; b.js
import a from './a' console.log(a) This volition work:
a.js
// noop b.js
import a from './a' panel.log('imported a:', a); output
imported a: object {}
Merely this will cause a alert:
a.js
var x = typeof ane; b.js
import a from './a' console.log('imported a:', a); output
imported a: undefined [HMR] bundle has 1 warnings ./b.js "export 'default' (imported as 'a') was not found in './a'
So
I recall the keyword typeof volition cause the ES/CommonJS module blazon distinguishing error.
In case this helps anyone …
Nosotros've just encountered this result, and eventually tracked it down to a superfluous inclusion of react in npm-shrinkwrap.json as a dependency of a dependency, equally well as existence included directly.
Removing "modules: false" in .babelrc might work
Faced this consequence when imported .js with ES6 class and module.exports = into my vue-cli project.
Webpack config:
{ test: /\.js$/, loader: 'babel-loader', include: [ resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/customer'), resolve('node_modules/my-class-module'), ] }, babel config:
{ "presets": [ ["env", { "modules": false, "useBuiltIns": true, }], "phase-two" ], "plugins": ["transform-vue-jsx", "transform-runtime"], } Included form:
class MyClass {} module.exports = MyClass; @kenberkeley it did solve for me, can y'all help explaining why would information technology piece of work ?
@bitcot I guessed, I tried, it worked, no caption...
For me the problem disappeared subsequently setting modules to "commonjs". Note that I was using 1 .babelrc file for both node environment and browser env.
"presets": [ ["@babel/env", { "useBuiltIns": "entry", "targets": ["> 5%", "ie 9"], "modules": "commonjs" }] ] @Zdend Notation that you lot'll miss out on tree shaking by doing that.
Now that Babel vii.x is out, I'll just say that this should essentially exist resolved. The only time y'all should see this, with Babel seven.ten, is if you're doing ane of:
- Y'all've actually using
importandmodule.exportsin the same file, which is not immune by Webpack. You can sidestep this by setting"modules": "commonjs", which will brand Babel compile theimportto arequire. This breaks tree shaking, every bit mentioned to a higher place though, and then fixing your code would be a better idea. - You're using
useBultins: 'entry'/'usage, or@babel/plugin-transform-runtime, and you lot 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, significant those transforms would insertimportstatements into your file, triggering case1.above. You can avoid this issue past settingsourceType: "unambiguous"in your Babel configuration, which volition tell it to gauge the type, similar Webpack does, instead of assuming all files are modules.
@Zdend You could exist hitting either or both of these cases, it is difficult to say.
@noppa @loganfsmyth thanks guys, tree shaking (or at least a big function of it) was actually disabled. Afterward removing modules attribute completely, client js bundles got considerably smaller.
It didn't withal fully enable tree shaking - when I tried to add a named consign function to a file that was only referenced by named imports and my new function wasn't used anywhere, fix sideEffects to imitation, the function was still included in the parcel.
This is my .babelrc for both client and server
{ "presets": [ [ "@boom-boom/env", { "targets": [ "> 5%", "ie 11" ] } ] ], "plugins": [ "@babel/plugin-transform-runtime", "@boom-boom/plugin-proposal-grade-properties", "@boom-boom/plugin-syntax-do-expressions", "@babel/plugin-proposal-do-expressions", "@boom-boom/transform-flow-strip-types", "@babel/plugin-proposal-nullish-coalescing-operator" ], "compact": false, "env": { "test": { "plugins": [ "dynamic-import-node" ] } }, "overrides": [ { "test": [ "**/src/scripts/**" ], "presets": [ "@babel/react" ], "plugins": [ "react-hot-loader/babel", "babel-plugin-flow-react-proptypes", "@babel/transform-menstruation-strip-types", "@boom-boom/syntax-dynamic-import" ] }, { "test": [ "**/server/**", "**/config/**" ], "sourceType": "unambiguous", "presets": [ [ "@babel/env", { "targets": { "node": "current" }, "modules": "commonjs" } ] ] } ] } Nonetheless, by doing that I broke my node server that relies on node_modules and my server side lawmaking which is only using import/export statements. The trouble is that one of the modules (newrelic) requires my config file (which uses import/export) but newrelic only expects sometime crave/ exports syntax but I likewise need to reference that file in files with import syntax so then either newrelic is happy or my code using import/export is happy. Of course if I run information technology with babel-node directly at that place are no issues, only if I try to precompile it. I likewise tried to whitelist a particular file in webpack-node-externals which didn't assistance, sourceType setting to unambiguous or removing useBuiltIns config or @babel/plugin-transform-runtime didn't help in my example or perhaps I didn't do information technology right.
{ mode: process.env.NODE_ENV || 'production', target: 'node', node: { __dirname: fake, __filename: false, }, externals: [nodeExternals({ whitelist: ['config/utils/config-file', 'newrelic/lib/config'] })], entry: { server: [ './server/index.js' ] }, output: { path: resolveRoot('/build-server'), filename: 'index.js' }, module: { rules: [{ test: /\.js$/, use: { loader: 'babel-loader' } }] }, bail: truthful } Thank you @loganfsmyth
Short answer。
If y'all are using babel 7 and bable-trunsform-runtime similar me, you can set:
"sourceType": "unambiguous", I solved this effect by replacing import with require in my code.
Yous tin can't mix import and module.exports
@sokra how difficult would it be to add a webpack compile error for this case? Seems there's room for a clearer explanation
Good afternoon,
I am using Vue two.5.16 and running into a similar trouble. After reading through this thread my issue withal perplexes me to why my console is throwing this error Cannot assign to read simply holding 'exports' of object '#<Object>'
I am bringing in this helper role using const helper = crave("../avails/helper/helper.js"); while using;
module.exports=simpleNoise: function(){this.perm = new Uint8Array(512);}
I have a larger part that I wish to export into my template, but I take isolated this line to be causing the error. The instantiation of a new Uint8Array() throw the error.
Whatever guidance on why this might be would be greatly appreciated.
I fixed this outcome by adding sourceType: 'unambiguous' in my babel config and removing "use strict"; before imports.
EDIT: I need to add modules: 'commonjs' to my @babel/preset-env options, for webpack, because I utilize babel-plugin-add-module-exports.
Using babel vii with webpack v4 this solved mine:
plugins: [
['@boom-boom/plugin-transform-modules-commonjs', {
'allowTopLevelThis': true
}]
]
@loganfsmyth yes I am using import and module.exports in the same file, however, setting 'modules': 'commonjs' throws a ReferenceError from Boom-boom which states: Using removed Boom-boom five option: modules - Use the corresponding module transform plugin in the 'plugins' option. Check out https://babeljs.io/docs/en/plugins#modules
Hence my reason of arriving at the above
@onyijne y'all get this error considering you added the module option in the wrong place. You have to set information technology as an choice of the env reset, not as a tiptop-level pick for babel.
Yeah that error means you did
presets: [ '@babel/preset-env', { modules: false } ] instead of
presets: [ ['@babel/preset-env', { modules: simulated } ] ] Note the extra set of square brackets.
I solved the problem by calculation modules: "cjs" to preset-env
["@babel/preset-env", { "loose": true, "targets": { "browsers": [ "ie >= ix", "> i%", "final ii versions" ] }, "useBuiltIns": "usage", "modules": "cjs" // the default value is auto }] @Javey : I tried your above solution. Information technology fixed this issue. Merely, now I am getting some other issue "TypeError: Invalid endeavour to spread non-iterable instance in
@Javey You are right. Information technology was a syntax error. Thanks for the fast reponse.
I solved the problem by adding "@babel/plugin-transform-modules-commonjs"
{ "presets": ["@boom-boom/preset-env"], "plugins": ["@babel/plugin-transform-runtime","@babel/plugin-transform-modules-commonjs"] } {
@zeroone001 that worked thank you!
The mutual causes of this issue are spelled out in https://github.com/webpack/webpack/problems/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 tin can provide with tree shaking.
Thanks for the information on this mistake.
I'm going to leave this comment here in case anyone else runs into the same issue I had which was caused past a different event, but manifested itself with this mistake.
Summary: I was unexpectedly getting this error in a library that shouldn't accept been transpiled, simply was accidentally beingness transpiled because information technology was linked during development.
(Oh, and literally just afterwards posting this I found the same issue here: https://github.com/vuejs/vue-cli/issues/2675#issuecomment-427021653)
Here'due south my simplified setup:
// parcel.json // Note that `dependencies` vs `devDependencies` does not impact this issue, // the aforementioned result would happen which e'er one was used. { "proper noun": "my-project", "dependencies": { "my-lib": "*" } } // webpack.config.js module.exports = { rules: [ { exam: /\.jsx?$/, exclude: [/node_modules/], // intention: exclude dependencies from transpilation utilize: [ { loader: 'babel-loader' } ] }, ], }; $ cd my-projection $ npm link my-lib # I want to endeavor out changes to my library during development // Within "my-project.js" const MyLib = require('my-lib'); // <-- would neglect with "Cannot assign to read but belongings 'exports' of object '#<Object>'" // I understand the error, but why is `my-lib` existence transpiled?? Expected behaviour:
I expected that the exclude regexp would exclude my-lib from transpilation - and for regular npm install or yarn install that is correct.
That is, I expected the my-lib to resolve to this path and exist excluded from transpilation:
/usr/code/my-project/node_modules/my-lib/my-lib.js
Actual behaviour:
However, because the library was symlinked during evolution, my-lib actually resolved to this path:
/usr/code/my-projection/node_modules/my-lib -> /usr/code/my-lib
So the library's actual on-disk path tested for exclusion was this:
/usr/lawmaking/my-lib/my-lib.js (Annotation that this real path does not include node_modules anywhere)
This meant the library was accidentally being included for transpilation because it didn't look like a dependency inside a mode_modules directory.
Solution:
The quick fix was to move my under-development code for the library nether a "faux" node_modules directory and link it from there.
This meant that the real on-disk path would successfully match against the exclude regexp: /usr/code/node_modules--dev/my-lib/my-lib.js
Now the library is excluded from transpilation, even when symlinked during evolution.
Had this issue today, adding this in .babelrc fixed it (https://github.com/webpack/webpack/issues/4039#issuecomment-419284940):
"sourceType": "unambiguous" The .babelrc file is a JSON at the root of your project. It should be taken into account by Boom-boom automatically. Hither's mine:
{ "sourceType": "unambiguous" } @STRsplit Ok, my bad :) Hopefully it will assist some others though! Can't aid you with babel.config.js.
@zeroone001: thx, that worked! (in my case in combination with webpack/babel-loader)
I solved this issue by adding "sourceType": "unambiguous" in my babelrc file
{ "presets": [ "@boom-boom/preset-env", "@boom-boom/preset-typescript", ], "plugins": [ "@boom-boom/plugin-transform-runtime", "@babel/plugin-syntax-dynamic-import" ], "comments": fake, "sourceType": "unambiguous" } After adding it, @babel/plugin-transform-runtme will inject crave expression instead of import in my commonjs files so they won't mix XD
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.
// babel.config.js const presets = [ [ "@boom-boom/preset-env", { useBuiltIns: "usage", corejs: "3", }, ], ]; const plugins = [ "@babel/plugin-proposal-class-properties", ]; module.exports = api => { api.cache(truthful); return { presets, plugins, } }; So preset-env would automatically import polyfills from core js inside my commonJS modules. for instance this file:
__webpack_require__.r(__webpack_exports__); /* WEBPACK VAR INJECTION */(part(module) {/* harmony import */ var core_js_modules_es_object_assign__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! core-js/modules/es.object.assign */ "./node_modules/core-js/modules/es.object.assign.js"); /* harmony import */ var core_js_modules_es_object_assign__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(core_js_modules_es_object_assign__WEBPACK_IMPORTED_MODULE_0__); // Some code.... role _defineProperty(obj, key, value) { if (primal in obj) { Object.defineProperty(obj, key, { value: value, enumerable: truthful, configurable: truthful, writable: true }); } else { obj[key] = value; } render obj; } // Some code.... module.exports = { WEBPACK_HOST_APP_LOCAL: WEBPACK_HOST_APP_LOCAL, WEBPACK_HOST_FBPAY_LOCAL: WEBPACK_HOST_FBPAY_LOCAL, ENVIRONMENTS: ENVIRONMENTS, WEBPACK_PORTS: WEBPACK_PORTS, WEBPACK_ESLINT_DEV: WEBPACK_ESLINT_DEV, WEBPACK_ESLINT_PROD: WEBPACK_ESLINT_PROD }; /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../node_modules/webpack/buildin/harmony-module.js */ "./node_modules/webpack/buildin/harmony-module.js")(module))) And so the import automatically inserted at the peak of my file and the module exports didn't play forth well i guess...
I hope i'm right 🤷♂️
I was also running into this problem when using @babel/preset-env with the useBuiltIns: 'usage' option, switching to core-js version 2 is what fixed it for me.
I was also using useBuiltIns: "usage" and didn't want to get back to [email protected] and for some reason sourceType: "unambiguous" merely moved the mistake OP (and I) had to the following fault:
TypeError: wrappedWellKnownSymbolModule.f is non a function occurring in most Webpack loaders during build.
After looking and searching for some time I stumbled over the following posts:
- https://github.com/symfony/webpack-encore/issues/552#issuecomment-480539276
- https://stackoverflow.com/a/52415747/4091702
Honestly, I don't sympathise what is going on here. But excluding core-js from Babel (every bit shown in the StackOverflow post) in conjunction with setting sourceType: "unambiguous" solved the issues I had with [email protected].
I'd dear if someone could explain the why and what, I cannot. But hopefully this helps the side by side guy stumbling over this event.
@pfeiferbit That sounds like it would be a compilation consequence unrelated to the issues here. Most likely, if yous're using i of the core-js import-injection plugins, and compiling core-js itself, you lot'll be injecting core-js imports into core-js itself, creating dependency cycles and errors like that one. You shouldn't run Babel on core-js so excluding it is the fashion to go. See https://github.com/babel/babel/problems/8754
was suddenly having this issue on a vue-cli project after trying out the four.0.blastoff.i
adding sourceType: 'unambiguous', to my babel.config.js file made the mistake go away
I actually simply got this to work by changing my
.babelrcfile.{ "presets": [ "es2015", "es2016", "stage-2" ], "plugins": [ "transform-async-to-generator", "transform-grade-backdrop", "transform-object-remainder-spread", "transform-export-extensions", "transform-runtime", "lodash" ] }The big modify that worked for me was removing
modules: falsefromes2015
this reply worked for me, thanks a lot
before:
"presets": [ [ "env", { "modules": fake, }
later on:
"presets": [ [ "env", { "modules": "commonjs", }
it seems to be .babelrc'south modules does't friction match commonjs.
here is the :https://www.babeljs.cn/docs/babel-preset-env docs
before:
"presets": [ [ "env", { "modules": false, }
after:
"presets": [ [ "env", { "modules": "commonjs", }
it seems to be .babelrc's modules does't match commonjs.
hither is the :https://world wide web.babeljs.cn/docs/babel-preset-env docs
![]()
"presets": [ ["@babel/preset-env", { "modules": "commonjs" }], "react-app" ], evn => @babel/preset-env
I really simply got this to work past changing my
.babelrcfile.{ "presets": [ "es2015", "es2016", "stage-2" ], "plugins": [ "transform-async-to-generator", "transform-class-properties", "transform-object-rest-spread", "transform-export-extensions", "transform-runtime", "lodash" ] }The large change that worked for me was removing
modules: imitationfromes2015
I have been struggling to find solution for the final 4 hours, this worked for me thank you!!!!
Adding sourceType: 'unambiguous', to my boom-boom.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)
Fixed mine by removing { "modules": fake } from this line in .babelrc: ["env", { "modules": false }]
If you don't want to employ boom-boom, my solution works.
I fixed this by making an entry point file like. node index.js
// index.js require = require('esm')(module) module.exports = require('./app.js') and whatsoever file I imported inside app.js and across worked with imports/exports
I fixed this by removing module:fake from .babelrc
Before
{ "presets": [ ["env", { "modules": faux, "targets": { "browsers": ["> one%", "last 2 versions", "not ie <= eight"] } }], "stage-ii" ], "plugins": ["transform-vue-jsx", "transform-runtime"], "env": { "test": { "presets": ["env", "stage-ii"], "plugins": ["transform-vue-jsx", "transform-es2015-modules-commonjs", "dynamic-import-node"] } } } Later
{ "presets": [ ["env", { "targets": { "browsers": ["> ane%", "last two versions", "non ie <= 8"] } }], "stage-ii" ], "plugins": ["transform-vue-jsx", "transform-runtime"], "env": { "test": { "presets": ["env", "stage-2"], "plugins": ["transform-vue-jsx", "transform-es2015-modules-commonjs", "dynamic-import-node"] } } } This configuration works for me.
webpack.config.js module.exports = { //... resolve: { // configuration options symlinks: imitation, } }; I accept a mix of imports and module.consign in aforementioned files, in almost threescore files, and I have got no event so far.
I fixed this by removing module:false from .babelrc
Before
{ "presets": [ ["env", { "modules": faux, "targets": { "browsers": ["> 1%", "last two versions", "non ie <= 8"] } }], "stage-2" ], "plugins": ["transform-vue-jsx", "transform-runtime"], "env": { "exam": { "presets": ["env", "stage-2"], "plugins": ["transform-vue-jsx", "transform-es2015-modules-commonjs", "dynamic-import-node"] } } }Later
{ "presets": [ ["env", { "targets": { "browsers": ["> ane%", "concluding 2 versions", "non ie <= 8"] } }], "stage-2" ], "plugins": ["transform-vue-jsx", "transform-runtime"], "env": { "test": { "presets": ["env", "stage-ii"], "plugins": ["transform-vue-jsx", "transform-es2015-modules-commonjs", "dynamic-import-node"] } } }
This worked for me as well, do you understand why though? I am and then perplexed
I am non mixing import with modules.consign, I use the post-obit with crave and it works on dev server:
const React = require('react') const charCodeOffset = 97 module.exports = { ... } I used a regular create-react-app, and added some barebones webpack/babel which I'yard not 100% sure are even beingness used but I can run npm run build.
module.exports = { module: { rules: [ { examination: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: "babel-loader" } } ] } }; babel.rc:
{ "presets": ["@babel/preset-env", "@boom-boom/preset-react"] } boom-boom.config.json:
module.exports = function (api) { api.cache(true); const presets = ["@boom-boom/preset-env", "@babel/preset-react"]; const plugins = []; return { sourceType: 'unambiguous', presets, plugins }; } package.json:
{ "name": "example", "version": "0.one.0", "private": truthful, "dependencies": { "@testing-library/jest-dom": "^iv.2.4", "@testing-library/react": "^ix.5.0", "@testing-library/user-event": "^7.2.ane", "animejs": "^three.2.0", "bootstrap": "^4.five.0", "express": "^iv.17.1", "prop-types": "^15.7.two", "react": "^xvi.13.1", "react-dom": "^16.13.1", "react-draggable": "^4.4.3", "react-resize-aware": "2.7.0", "react-router": "^five.ii.0", "react-router-dom": "^5.ii.0", "react-scripts": "3.4.ane" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "examination": "react-scripts exam", "squirt": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not expressionless", "not op_mini all" ], "development": [ "last ane chrome version", "final 1 firefox version", "terminal 1 safari version" ] }, "devDependencies": { "@babel/core": "^7.10.5" }, "babel": { "presets": [ "@babel/preset-env", "@babel/preset-react" ], "plugins": [] } } Any ideas why that fault would still evidence up in product? Both on AWS Amplify server and local production run.
For now I changed the module.exports file to export default and it worked. I have a lot of mixed syntax between ES6 and CommonJS probably and I volition have to look into properly setting upwards Babel and Webpack...
In my react-native-spider web case, just use an additional webpack dominion, and then the TypeError: Cannot assign to read only belongings 'exports' of object is fixed. Possibly you can ref to it.
npm install --salve-dev react-app-rewired
Create a config-overrides.js in your projection root
// used by react-app-rewired const webpack = require('webpack'); const path = require('path'); module.exports = { webpack: function (config, env) { config.module.rules[1].utilise[0].options.baseConfig.extends = [ path.resolve('.eslintrc.js'), ]; // To let allonym like 'react-native/Libraries/Components/StaticRenderer' // take effect, must set it before allonym 'react-native' delete config.resolve.alias['react-native']; config.resolve.allonym['react-native/Libraries/Components/StaticRenderer'] = 'react-native-spider web/dist/vendor/react-native/StaticRenderer'; config.resolve.alias['react-native'] = path.resolve( 'web/aliases/react-native', ); // Let'southward strength our code to package using the same bundler react native does. config.plugins.push( new webpack.DefinePlugin({ __DEV__: env === 'development', }), ); // Demand this rule to foreclose `Attempted import fault: 'SOME' is non exported from` when `react-app-rewired build` // Need this rule to forestall `TypeError: Cannot assign to read just property 'exports' of object` when `react-app-rewired commencement` config.module.rules.button({ test: /\.(js|tsx?)$/, // Yous can exclude the exclude belongings if you don't want to go on adding individual node_modules // merely continue an center on how it furnishings your build times, for this case it's negligible // exclude: /node_modules[/\\]([electronic mail protected]|react-native-gesture-handler|react-native-screens)/, use: { loader: 'babel-loader', }, }); return config; }, paths: function (paths, env) { paths.appIndexJs = path.resolve('index.web.js'); paths.appSrc = path.resolve('.'); paths.moduleFileExtensions.push('ios.js'); return paths; }, }; Also create a web/aliases/react-native/index.js
// ref to https://levelup.gitconnected.com/react-native-typescript-and-react-native-web-an-arduous-but-rewarding-journey-8f46090ca56b import {Text equally RNText, Prototype as RNImage} from 'react-native-spider web'; // Let's export everything from react-native-web export * from 'react-native-spider web'; // And let's stub out everything that'due south missing! consign const ViewPropTypes = { fashion: () => {}, }; RNText.propTypes = { style: () => {}, }; RNImage.propTypes = { style: () => {}, source: () => {}, }; export const Text = RNText; consign const Epitome = RNImage; // consign const ToolbarAndroid = {}; export const requireNativeComponent = () => {}; Now yous tin just run react-app-rewired start instead of react-scripts commencement
@flyskywhy thank you a lot, this saved me a 24-hour interval of work!!!! Sending karma your way 👏
https://babeljs.io/docs/en/options#sourcetype
"script" - Parse the file using the ECMAScript Script grammar. No import/export statements allowed, and files are not in strict mode.
"module" - Parse the file using the ECMAScript Module grammar. Files are automatically strict, and import/export statements are allowed.
"unambiguous" - Consider the file a "module" if import/export statements are present, or else consider it a "script".
Given that the default for sourcetype is "module", I wonder why Boom-boom doesn't treat the presence of module.exports (and the absence important/export statements) as a signal that the file should be parsed as "script" instead, to avert throwing this error.
Source: https://bleepcoder.com/webpack/201799135/cannot-assign-to-read-only-property-exports-of-object-object
0 Response to "React Cannot Assign to Read Only Property"
Post a Comment