Unhandled Rejection (Typeerror): Cannot Assign to Read Only Property 'exports' of Object '#<object>'
The lawmaking above is ok. Yous tin mix crave
and export
. You tin can't mix import
and module.exports
.
@sokra probably in existent code I had something more, that acquired the issue. Now I've refactored this part to import export
and it works fine.
I'll try check information technology in more articulate example. For at present I believe the issue can be airtight.
This outcome was newly affecting me after instructing Babel to not transpile module syntax. As sokra described, information technology but occurred when trying to use CommonJS fashion module.exports
inside of ES modules. require
always works. This tin can be fixed past merely replacing all module.exports = ...
to consign default ...
where applicable, every bit this is seemingly equivalent for old Babel-way ES module transpilation. (Note though, that importing this module using crave
will probably give you an selection with a default
central rather than the default export itself, so it's probably best you make the switch across the entire codebase at one time.)
I notice myself besides existence bitten by this outcome since upgrading to 2.two.0
. In my case, my hypothesis is a require chain that looks like:
CommonJSModule --requires--> ESModule --requires--> AnotherCommonJSModule
I'1000 deplorable that I tin can't provide whatever more details at this fourth dimension.
Taking a quick glance, this is definitely the culprit:
https://github.com/webpack/webpack/commit/a7a41848c73f14ff294b48285f42063e1f0de4b1
discover harmony modules before parsing exports is now undefined in ESM module.exports is now read-only in ESM and returns undefined define is at present undefined in ESM
Every bit it says, module.exports
is read-simply in ES modules. If you're getting module.exports
every bit read-only in a CommonJS module, THAT would be a problems, but that file is very much non a CommonJS file if it contains whatever export
/import
statements. I can confirm that this was the problem in my instance and it was fixed by making my ES modules properly use ES exports. As a note require
still works just fine inside of whatsoever module.
From my PoV it seems like Webpack's new behavior ultimately makes a lot more sense than the former behavior. It is adequately inane to allow mixing of import
statements and CommonJS module.exports
, and probably was never intended to work that way.
Peradventure add together this info to migration guide?
I tin can simply speak for myself, merely for the situation affecting me the module inside which module.exports
is read-only does not have any import
or export
statements. It appears that the heuristic that is identifying the file in question equally a 'harmony' model is misfiring in some situations.
@ggoodman are yous using babel-runtime?
@sokra here are the relevant config files:
.babelrc:
{ "presets": [ ["env", { "modules": false, "targets": { "browsers": ["last two versions", "safari >= 7"] } }] ], "plugins": ["transform-runtime", "syntax-dynamic-import"] }
webpack.config.js (simplified):
'utilise strict'; const ExtractTextPlugin = require('excerpt-text-webpack-plugin'); const Path = require('path'); const Webpack = require('webpack'); const config = { cache: true, devtool: process.env.NODE_ENV !== 'production' ? 'source-map' : simulated, context: Path.join(__dirname), output: { path: Path.join(__dirname, 'build'), filename: '[name].js', chunkFilename: '[name].js', publicPath: '/static/', }, recordsPath: Path.join(__dirname, 'recordsCache'), module: { rules: [{ test: /\js$/, exclude: /node_modules/, use: [ { loader: 'ng-annotate-loader', }, { loader: 'babel-loader', options: { cacheDirectory: true, }, }, { loader: 'cord-replace-loader', options: { multiple: [ { search: /API_URL/k, replace: procedure.env['PLUNKER_API_URL'] }, { search: /EMBED_URL/g, supplant: process.env['PLUNKER_EMBED_URL'] }, { search: /RUN_URL/chiliad, replace: process.env['PLUNKER_RUN_URL'] }, { search: /SHOT_URL/g, supersede: procedure.env['PLUNKER_SHOT_URL'] }, { search: /WWW_URL/g, replace: process.env['PLUNKER_WWW_URL'] }, ], }, }, ] }, ], }, plugins: [ new ExtractTextPlugin({ filename: '[name].css', disable: false, allChunks: true, }), ], resolve: { modules: [ Path.join(__dirname, 'node_modules'), Path.join(__dirname, 'src'), ], }, }; module.exports = config;
Chiming in every bit I'm getting this error in the browser every bit well, merely neither the requiring module, nor the required module accept whatsoever import
or export
statements in them. I am using transform-runtime
if that'due south relevant.
transform-runtime
adds import
to your files...
@sokra I was not aware that this plugin would add import
to my files.
If removing that plugin is a solution, what alternative tin can we consider so that nosotros don't accept babel-runtime
stuff like _classCallCheck
included for every source file using ES6 features like class
es?
The way I see it, there are a few proficient solutions:
- Make
transform-runtime
support outputtingrequire
statements instead ofimport
statements, every bit an option. This seems unlikely, considering information technology looks like Babel is already relying on the fact thatimport
is declarative. - Use
transform-es2015-modules-commonjs
. This would replace allimport
statements withcrave
statements. If you are not using anyimport
/export
syntax in your app, this solution is probably ideal, considering information technology incurs no extra cost. However, if y'all are using ES modules, then this will probable impact Webpack 2'due south ability to perform tree shaking. (I'm sure everyone is aware of this.) - Use ES modules across the board. I think this is the nearly correct thing to do. Is at that place a reason why existing CommonJS exports can't merely be migrated?
require
does not take to exist globally replaced, onlymodule.exports
andexports
statements.
How i tin can reproduce module.exports beliefs?
I had entry betoken with proper name LoginPage, i need to build library with the same proper name, after that i init information technology on the page using new LoginPage();
Now i should use new LoginPage.LoginPage() or new LoginPage.default();
How i tin resolve this issue?
calculation import
(by transform-runtime
) as well means that the file is switched into strict manner, which could intermission you lawmaking. In my opinion transform-runtime
should be inverse.
I had the post-obit .babelrc
{ "presets": [ [ "es2015", { "modules": false } ], "stage-0", "react" ], "plugins": [ "add-module-exports", "transform-class-properties", "transform-object-rest-spread", "transform-object-assign" ] }
And was able to set this by removing the add-module-exports
plugin. TBH, I tin't even recall why I had it in there to begin with... but upon removal it started working as expected. Nobody else has mentioned add-module-exports
yet so I thought I'd chime in too to point out that information technology'south non merely transform-runtime
causing this.
I am having the same problem with vis project. I made the most elementary example if somebody have any idea what could exist the trouble. Error is in vis code. https://github.com/almende/vis
It does non seam like related to any plugin or mixing of import and module.exports.
fault:
Uncaught TypeError: Cannot assign to read but belongings '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
example:
https://github.com/primozs/vis-case-webpack2
I had no issues in versions:
"webpack": "2.ane.0-beta.27", "webpack-dev-server": "v2.1.0-beta.12",
@johnwchadwick I merely upgraded ane of my project to Webpack ii.ii.x and it fixed my issue. Thank you.
Replaced module.exports
with consign default
, and the crave(...)
with require(...).default
Unfortunately the exports-loader injects module.exports statements so using it with a legacy codebase and injecting that to a es6 projection has go impossible.
Is in that location whatever progress on this? I am unable to import a legacy library. Unfortunately i am unable to utilize import / export in legacy library.
@hzoo Hey is at that place a manner to let transform-runtime apply require instead important'southward
I actually simply 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 modify that worked for me was removing modules: false
from es2015
@TheLarkInn Definitely something nosotros can explore for 7.0
. There are several issues around transform-runtime that have been longstanding that we're hoping to gear up.
@loganfsmyth Awesome only wanted to followup. Should we rail this or you lot all? Doing some issue purging this week lol.
But bumped into this myself. There should probably be an eslint dominion that disallows using import
in a file with module.exports
. Anyone know whether this exists? If non, I'll make information technology :)
ä˝ ćŠŠmodule.export改为export.default试试
@smitt04 :
The big change that worked for me was removing modules: faux from es2015 đź‘Ť 2
This will suspension tree shaking.
Better approach would be to replace module.exports with exports default. Will that work for you lot?
@abhinavsingi unfortunately I tin can't utilise exports default. I use that in all my own new code. Simply the problem was when I imported a node module that was using module.exports
Right now, i don't think information technology is correct to use import / export on node js modules, until node supports them natively. Client side lawmaking is ok to transpile since nosotros can't write a lot of es6+ in browsers and usually y'all have a build / minify stage on deployment. Merely having to transpile your code to run on node i call up is an extra pace that doesn't need to exist done. Now i take to compile / transpile my lawmaking be fore testing.
what is the recommended solution for this outcome when a dependent npm module is performing an import when they shouldn't? Is in that location whatsoever style to have webpack automatically alter the import blah from 'blah'
to var blah = crave('blah').default
?
@kentcdodds PR non really an selection every bit the module devs are trying to determine on which manner to prefer, ane.5 months ago, can't forcefulness someone else to accept a PR to resolve a bundling effect.
@patsissons, I can appreciate that. Forking is e'er an option. Yous could too write a custom loader for that module I gauge... Though at that place's probably an easier way...
I submitted a PR none the less, https://github.com/almende/vis/pull/3063
This effect just ways I accept to packet 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 dominion???? It can certainly cause a lot of trouble! Every module has to be rewrite
I had this trouble when I had one file with mix of export default
and require('...')
. I'm ok with changing it, but is it possible to enhance an exception on webpack build step?
Guys, would be cool to add together link to current issue into fault on mixed import
and module.exports
Is it possible and reasonable?
Guys, would be absurd to add together link to current upshot into error on mixed import and module.exports
Is information technology possible and reasonable?
I would take a PR for that @a-x- feel free and tag me when y'all create it.
Information technology's clear that this upshot happens when import
and module.exports
are mixed.
As well it'southward clear that the possible solution, such as removing modules:false
from the ['es2015', {modules: false}]
equasion is not skilful, every bit it affects tree shaking.
Have 2 questions though:
- I thought that if I will
crave
my module on the front-cease side (explicitly) this would solve the consequence. Asmodule.exports
module would existrequired
. But I see the aforementioned error. Why? - Why I don't see such error for `React, for instance. In my lawmaking, as the aforementioned file I accept:
import React, {Component} from 'react'; import Workflow from 'mutual/modules/workflow';
whily react
leads to:
And workflow
leads to:
In the panel I see the error about the workflow inclusion:
how the react
example is dissimilar?
- What is the expected way to have an isomorphic modules and use it both on
nodejs
andfront-end
parts. (I don't want to transpile my nodejs code)
@sokra
Regards,
You have to transpile your node code since node doesn't support import/export.
@ljharb
thanks for the answer.
why I don't have the same issue while importing the react
?
I presume because Workflow is using export syntax, and React, equally a published library, is using module.exports. Non actually sure tho.
If so this particular feature looks non very thought through. I recollect there should exist a way for the developer to take an isomorphic modules for nodejs and webpack. This is very natural need.
The but way to do that is to always transpile everything using babel and webpack.
@ljharb
but that's the thing :) I don't want to transpile everything. nodejs has enough ES2015 features to not be transpiled. even async/await
. so it feels right to run the original code.
And then the codes not truly isomorphic, because you're not using the same output on both platforms. Yous can't have it both ways :-)
Howdy @sokra ,
I know you're decorated.
But the question from https://github.com/webpack/webpack/issues/4039#issuecomment-309746398 , why I tin can import from 'react'
but can not import my custom module, while they both practise module.exports
- doesn't allow me to sleep :)
Please, consider pointing me to the right management.
Thanks in advance.
Regards,
@PavelPolyakov looks like you lot use module.exports = Workflow
, simply somewhere in a higher place your're exporting dependencies using export
, instead of require
. Can you make sure that you don't take import
or export
statements in your Workflow.js
?
hi @KELiON, thanks for trying to help.
No, there are no imports
to a higher place.
The modules configuration, as it is stated above is important as well:
presets: [['es2015', {modules: simulated}], 'react'],
Whenever I comment it out information technology works, whether I use imports
or crave
.
@KELiON , @ljharb
I believe I found the effect why it works for the node_modules
, but not for the regular modules.
And the issue was - that node_modules
are excluded from the babel-loader
.
Probably, when boom-boom-loader
meets module.exports
something goes incorrect.
@PavelPolyakov you should mail service a reproduction of your issue instead of snippets. It will make information technology a lot easier for others to follow and diagnose the issue.
[e-mail protected]
This will piece of work:
a.js
module.exports = {};
b.js
import a from './a' panel.log(a)
But this will not work:
a.js
// the occurrence of keyword `typeof` will lead to error: // `Uncaught TypeError: Cannot assign to read only holding 'exports' of object '#<Object>'` var x = typeof 1; module.exports = {};
b.js
import a from './a' console.log(a)
This will work:
a.js
// noop
b.js
import a from './a' panel.log('imported a:', a);
output
imported a: object {}
But this will cause a warning:
a.js
var x = typeof i;
b.js
import a from './a' console.log('imported a:', a);
output
imported a: undefined [HMR] parcel has i warnings ./b.js "export 'default' (imported every bit 'a') was not found in './a'
And so
I think the keyword typeof
volition cause the ES/CommonJS module type distinguishing fault.
In example this helps anyone …
We've merely encountered this issue, and eventually tracked it downwards to a superfluous inclusion of react
in npm-shrinkwrap.json
as a dependency of a dependency, equally well as being included directly.
Removing "modules: false"
in .babelrc might piece of work
Faced this result when import
ed .js
with ES6 class
and module.exports =
into my vue-cli
project.
Webpack config:
{ exam: /\.js$/, loader: 'babel-loader', include: [ resolve('src'), resolve('exam'), resolve('node_modules/webpack-dev-server/client'), resolve('node_modules/my-class-module'), ] },
babel config:
{ "presets": [ ["env", { "modules": false, "useBuiltIns": true, }], "phase-2" ], "plugins": ["transform-vue-jsx", "transform-runtime"], }
Included class:
grade MyClass {} module.exports = MyClass;
@kenberkeley it did solve for me, can y'all help explaining why would it work ?
@bitcot I guessed, I tried, it worked, no caption...
For me the trouble disappeared after setting modules to "commonjs". Note that I was using ane .babelrc file for both node environs and browser env.
"presets": [ ["@boom-boom/env", { "useBuiltIns": "entry", "targets": ["> 5%", "ie ix"], "modules": "commonjs" }] ]
@Zdend Note that you lot'll miss out on tree shaking past doing that.
At present that Boom-boom 7.10 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:
- You've actually using
import
andmodule.exports
in the same file, which is not immune by Webpack. Y'all tin 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. - You're using
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). Boom-boom assumes files are ES modules by default, pregnant those transforms would insertimport
statements into your file, triggering casei.
to a higher place. Yous tin can avert this consequence by settingsourceType: "unambiguous"
in your Babel configuration, which volition tell it to guess the blazon, like Webpack does, instead of assuming all files are modules.
@Zdend You could be hitting either or both of these cases, information technology is hard to say.
@noppa @loganfsmyth thanks guys, tree shaking (or at least a big function of it) was really disabled. Afterward removing modules attribute completely, customer js bundles got considerably smaller.
Information technology didn't withal fully enable tree shaking - when I tried to add a named export role to a file that was but referenced by named imports and my new office wasn't used anywhere, set up sideEffects to false, the function was still included in the packet.
This is my .babelrc for both client and server
{ "presets": [ [ "@babel/env", { "targets": [ "> 5%", "ie 11" ] } ] ], "plugins": [ "@babel/plugin-transform-runtime", "@boom-boom/plugin-proposal-class-properties", "@babel/plugin-syntax-do-expressions", "@boom-boom/plugin-proposal-practise-expressions", "@boom-boom/transform-flow-strip-types", "@babel/plugin-proposal-nullish-coalescing-operator" ], "compact": imitation, "env": { "test": { "plugins": [ "dynamic-import-node" ] } }, "overrides": [ { "test": [ "**/src/scripts/**" ], "presets": [ "@babel/react" ], "plugins": [ "react-hot-loader/boom-boom", "babel-plugin-flow-react-proptypes", "@babel/transform-flow-strip-types", "@boom-boom/syntax-dynamic-import" ] }, { "test": [ "**/server/**", "**/config/**" ], "sourceType": "unambiguous", "presets": [ [ "@babel/env", { "targets": { "node": "current" }, "modules": "commonjs" } ] ] } ] }
However, by doing that I bankrupt my node server that relies on node_modules and my server side code which is but using import/export statements. The problem is that one of the modules (newrelic) requires my config file (which uses import/export) but newrelic only expects old require/ exports syntax just I also need to reference that file in files with import syntax so then either newrelic is happy or my lawmaking using import/export is happy. Of grade if I run it with babel-node direct there are no issues, only if I try to precompile information technology. I also tried to whitelist a detail file in webpack-node-externals which didn't help, sourceType setting to unambiguous or removing useBuiltIns config or @boom-boom/plugin-transform-runtime didn't help in my instance or perhaps I didn't practice it right.
{ mode: process.env.NODE_ENV || 'production', target: 'node', node: { __dirname: false, __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: [{ examination: /\.js$/, use: { loader: 'boom-boom-loader' } }] }, bond: truthful }
Thanks @loganfsmyth
Short answer。
If you are using babel 7 and bable-trunsform-runtime
like me, you can set up:
"sourceType": "unambiguous",
I solved this outcome past replacing import
with crave
in my code.
You can't mix import and module.exports
@sokra how difficult would information technology be to add a webpack compile mistake for this case? Seems there's room for a clearer explanation
Good afternoon,
I am using Vue 2.five.16 and running into a similar trouble. After reading through this thread my upshot however perplexes me to why my panel is throwing this mistake 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 accept 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.
Whatsoever guidance on why this might be would be greatly appreciated.
I fixed this issue by adding sourceType: 'unambiguous'
in my boom-boom config and removing "use strict";
before import
south.
EDIT: I need to add modules: 'commonjs'
to my @babel/preset-env
options, for webpack, considering I utilise babel-plugin-add-module-exports
.
Using boom-boom seven with webpack v4 this solved mine:
plugins: [
['@babel/plugin-transform-modules-commonjs', {
'allowTopLevelThis': true
}]
]
@loganfsmyth yes I am using import and module.exports in the aforementioned file, however, setting 'modules': 'commonjs' throws a ReferenceError from Boom-boom which states: Using removed Babel 5 option: modules - Use the corresponding module transform plugin in the 'plugins' pick. Cheque out https://babeljs.io/docs/en/plugins#modules
Hence my reason of arriving at the above
@onyijne y'all become this error considering yous added the module
option in the wrong identify. You have to set up it as an option of the env reset, not every bit a top-level selection for boom-boom.
Aye that error means you did
presets: [ '@babel/preset-env', { modules: faux } ]
instead of
presets: [ ['@babel/preset-env', { modules: fake } ] ]
Note the extra set of square brackets.
I solved the problem by adding modules: "cjs"
to preset-env
["@babel/preset-env", { "loose": true, "targets": { "browsers": [ "ie >= ix", "> 1%", "final 2 versions" ] }, "useBuiltIns": "usage", "modules": "cjs" // the default value is auto }]
@Javey : I tried your higher up solution. It stock-still this effect. Merely, now I am getting another issue "TypeError: Invalid try to spread non-iterable instance in
@Javey You are right. It was a syntax error. Thanks for the fast reponse.
I solved the problem by adding "@babel/plugin-transform-modules-commonjs"
{ "presets": ["@babel/preset-env"], "plugins": ["@babel/plugin-transform-runtime","@babel/plugin-transform-modules-commonjs"] }
{
@zeroone001 that worked thank you!
The common causes of this issue are spelled out in https://github.com/webpack/webpack/bug/4039#issuecomment-419284940
While force-loading @babel/plugin-transform-modules-commonjs
technically works, information technology is not what I would recommend since it essentially disables many of the benefits Webpack can provide with tree shaking.
Thanks for the data on this error.
I'm going to exit this comment here in case anyone else runs into the same issue I had which was caused by a different issue, but manifested itself with this error.
Summary: I was unexpectedly getting this fault in a library that shouldn't accept been transpiled, but was accidentally being transpiled considering it was linked during development.
(Oh, and literally but after posting this I found the same issue here: https://github.com/vuejs/vue-cli/issues/2675#issuecomment-427021653)
Here's my simplified setup:
// package.json // Note that `dependencies` vs `devDependencies` does not bear on this issue, // the same result would happen which ever i was used. { "proper noun": "my-projection", "dependencies": { "my-lib": "*" } }
// webpack.config.js module.exports = { rules: [ { test: /\.jsx?$/, exclude: [/node_modules/], // intention: exclude dependencies from transpilation use: [ { loader: 'babel-loader' } ] }, ], };
$ cd my-project $ npm link my-lib # I want to try out changes to my library during development
// Inside "my-project.js" const MyLib = require('my-lib'); // <-- would neglect with "Cannot assign to read only belongings 'exports' of object '#<Object>'" // I understand the error, but why is `my-lib` being 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 right.
That is, I expected the my-lib
to resolve to this path and exist excluded from transpilation:
/usr/lawmaking/my-project/node_modules/my-lib/my-lib.js
Actual behaviour:
Nevertheless, because the library was symlinked during development, my-lib
really resolved to this path:
/usr/code/my-project/node_modules/my-lib
-> /usr/code/my-lib
And then the library'southward actual on-deejay path tested for exclusion was this:
/usr/code/my-lib/my-lib.js
(Notation that this real path does not include node_modules
anywhere)
This meant the library was accidentally being included for transpilation because it didn't await similar a dependency inside a mode_modules
directory.
Solution:
The quick fix was to move my under-evolution code for the library under a "fake" node_modules
directory and link information technology from there.
This meant that the real on-deejay path would successfully lucifer confronting the exclude
regexp: /usr/code/node_modules--dev/my-lib/my-lib.js
Now the library is excluded from transpilation, fifty-fifty when symlinked during evolution.
Had this upshot 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 Babel automatically. Here'southward mine:
{ "sourceType": "unambiguous" }
@STRsplit Ok, my bad :) Hopefully it will help some others though! Tin can't aid yous with boom-boom.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": [ "@babel/preset-env", "@boom-boom/preset-typescript", ], "plugins": [ "@babel/plugin-transform-runtime", "@babel/plugin-syntax-dynamic-import" ], "comments": false, "sourceType": "unambiguous" }
Subsequently adding it, @babel/plugin-transform-runtme
will inject require
expression instead of import
in my commonjs files and so they won't mix XD
I remember 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-grade-properties", ]; module.exports = api => { api.cache(true); return { presets, plugins, } };
So preset-env
would automatically import polyfills from core js inside my commonJS modules. for example this file:
__webpack_require__.r(__webpack_exports__); /* WEBPACK VAR INJECTION */(function(module) {/* harmony import */ var core_js_modules_es_object_assign__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! cadre-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.... function _defineProperty(obj, primal, value) { if (primal in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: truthful, writable: truthful }); } else { obj[primal] = value; } return 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 */}.phone call(this, __webpack_require__(/*! ./../node_modules/webpack/buildin/harmony-module.js */ "./node_modules/webpack/buildin/harmony-module.js")(module)))
Then the import
automatically inserted at the top of my file and the module exports didn't play along well i guess...
I hope i'thousand right 🤷♂️
I was too running into this trouble when using @babel/preset-env
with the useBuiltIns: 'usage'
option, switching to core-js
version ii is what fixed it for me.
I was also using useBuiltIns: "usage"
and didn't want to go back to [email protected]
and for some reason sourceType: "unambiguous"
simply moved the error OP (and I) had to the following fault:
TypeError: wrappedWellKnownSymbolModule.f is non a function
occurring in most Webpack loaders during build.
Later on 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 understand what is going on here. But excluding core-js from Babel (every bit shown in the StackOverflow postal service) in conjunction with setting sourceType: "unambiguous"
solved the bug I had with [email protected]
.
I'd love if someone could explicate the why and what, I cannot. Just hopefully this helps the next guy stumbling over this issue.
@pfeiferbit That sounds like information technology would be a compilation issue unrelated to the problems here. Near likely, if you're using one of the core-js
import-injection plugins, and compiling core-js
itself, you'll be injecting core-js
imports into cadre-js
itself, creating dependency cycles and errors like that one. You lot shouldn't run Boom-boom on core-js
so excluding it is the mode to go. Come across https://github.com/babel/boom-boom/issues/8754
was suddenly having this issue on a vue-cli project after trying out the iv.0.alpha.i
calculation sourceType: 'unambiguous',
to my babel.config.js file made the error go abroad
I actually only got this to piece of work by changing my
.babelrc
file.{ "presets": [ "es2015", "es2016", "phase-ii" ], "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: faux
fromes2015
this reply worked for me, thanks a lot
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://world wide web.babeljs.cn/docs/babel-preset-env docs
before:
"presets": [ [ "env", { "modules": faux, }
after:
"presets": [ [ "env", { "modules": "commonjs", }
information technology seems to be .babelrc's modules does't match commonjs.
here is the :https://www.babeljs.cn/docs/babel-preset-env docs
![]()
"presets": [ ["@babel/preset-env", { "modules": "commonjs" }], "react-app" ],
evn => @babel/preset-env
I actually just got this to piece of work by changing my
.babelrc
file.{ "presets": [ "es2015", "es2016", "phase-2" ], "plugins": [ "transform-async-to-generator", "transform-class-properties", "transform-object-balance-spread", "transform-export-extensions", "transform-runtime", "lodash" ] }
The large change that worked for me was removing
modules: false
fromes2015
I take been struggling to find solution for the terminal iv hours, this worked for me thank you!!!!
Calculation sourceType: 'unambiguous'
, to my boom-boom.config.js fixed things for me.
I wouldn't commonly annotate like this, but this result was one of the first links I opened from google and I missed the solution: https://github.com/webpack/webpack/problems/4039#issuecomment-419284940. (mode up over a year agone)
Fixed mine by removing { "modules": false } from this line in .babelrc: ["env", { "modules": faux }]
If you don't desire to employ babel, 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 any file I imported inside app.js
and beyond worked with imports/exports
I fixed this by removing module:false from .babelrc
Before
{ "presets": [ ["env", { "modules": simulated, "targets": { "browsers": ["> one%", "final 2 versions", "not ie <= 8"] } }], "stage-2" ], "plugins": ["transform-vue-jsx", "transform-runtime"], "env": { "test": { "presets": ["env", "stage-two"], "plugins": ["transform-vue-jsx", "transform-es2015-modules-commonjs", "dynamic-import-node"] } } }
After
{ "presets": [ ["env", { "targets": { "browsers": ["> 1%", "concluding 2 versions", "non ie <= viii"] } }], "phase-2" ], "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: false, } };
I accept a mix of imports and module.consign in same files, in most 60 files, and I have got no issue so far.
I fixed this by removing module:false from .babelrc
Before
{ "presets": [ ["env", { "modules": false, "targets": { "browsers": ["> 1%", "concluding 2 versions", "not ie <= 8"] } }], "phase-2" ], "plugins": ["transform-vue-jsx", "transform-runtime"], "env": { "test": { "presets": ["env", "stage-2"], "plugins": ["transform-vue-jsx", "transform-es2015-modules-commonjs", "dynamic-import-node"] } } }
After
{ "presets": [ ["env", { "targets": { "browsers": ["> 1%", "last 2 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"] } } }
This worked for me also, exercise you understand why though? I am so perplexed
I am not mixing import with modules.export, I apply the following with require 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/boom-boom which I'k non 100% sure are fifty-fifty being used only I tin can run npm run build
.
module.exports = { module: { rules: [ { exam: /\.(js|jsx)$/, exclude: /node_modules/, apply: { loader: "babel-loader" } } ] } };
boom-boom.rc:
{ "presets": ["@babel/preset-env", "@babel/preset-react"] }
boom-boom.config.json:
module.exports = role (api) { api.cache(true); const presets = ["@babel/preset-env", "@babel/preset-react"]; const plugins = []; return { sourceType: 'unambiguous', presets, plugins }; }
parcel.json:
{ "proper noun": "example", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^4.2.4", "@testing-library/react": "^9.5.0", "@testing-library/user-event": "^7.2.1", "animejs": "^3.2.0", "bootstrap": "^iv.v.0", "limited": "^iv.17.one", "prop-types": "^xv.7.2", "react": "^16.13.i", "react-dom": "^xvi.13.1", "react-draggable": "^four.four.3", "react-resize-aware": "2.7.0", "react-router": "^5.2.0", "react-router-dom": "^v.2.0", "react-scripts": "3.4.i" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "product": [ ">0.ii%", "not expressionless", "non op_mini all" ], "development": [ "last 1 chrome version", "terminal 1 firefox version", "final 1 safari version" ] }, "devDependencies": { "@babel/cadre": "^7.10.v" }, "babel": { "presets": [ "@babel/preset-env", "@babel/preset-react" ], "plugins": [] } }
Any ideas why that error would still show up in production? Both on AWS Amplify server and local production run.
For at present I changed the module.exports file to consign default
and it worked. I accept a lot of mixed syntax between ES6 and CommonJS probably and I will have to look into properly setting up Boom-boom and Webpack...
In my react-native-web case, just employ an additional webpack rule, and so the TypeError: Cannot assign to read but property 'exports' of object
is fixed. Perhaps you can ref to it.
npm install --relieve-dev react-app-rewired
Create a config-overrides.js
in your project root
// used by react-app-rewired const webpack = require('webpack'); const path = require('path'); module.exports = { webpack: part (config, env) { config.module.rules[one].use[0].options.baseConfig.extends = [ path.resolve('.eslintrc.js'), ]; // To let alias like 'react-native/Libraries/Components/StaticRenderer' // have consequence, must set it earlier alias 'react-native' delete config.resolve.alias['react-native']; config.resolve.alias['react-native/Libraries/Components/StaticRenderer'] = 'react-native-web/dist/vendor/react-native/StaticRenderer'; config.resolve.alias['react-native'] = path.resolve( 'spider web/aliases/react-native', ); // Let's forcefulness our code to bundle using the aforementioned bundler react native does. config.plugins.push( new webpack.DefinePlugin({ __DEV__: env === 'development', }), ); // Need this rule to foreclose `Attempted import error: 'SOME' is not exported from` when `react-app-rewired build` // Need this rule to prevent `TypeError: Cannot assign to read merely property 'exports' of object` when `react-app-rewired start` config.module.rules.push({ exam: /\.(js|tsx?)$/, // You can exclude the exclude belongings if you lot don't want to keep adding private node_modules // only continue an middle on how it effects your build times, for this case it's negligible // exclude: /node_modules[/\\]([email protected]|react-native-gesture-handler|react-native-screens)/, use: { loader: 'babel-loader', }, }); return config; }, paths: office (paths, env) { paths.appIndexJs = path.resolve('index.spider web.js'); paths.appSrc = path.resolve('.'); paths.moduleFileExtensions.push('ios.js'); render paths; }, };
Also create a spider web/aliases/react-native/alphabetize.js
// ref to https://levelup.gitconnected.com/react-native-typescript-and-react-native-spider web-an-arduous-but-rewarding-journeying-8f46090ca56b import {Text equally RNText, Epitome every bit RNImage} from 'react-native-web'; // Allow's export everything from react-native-web export * from 'react-native-web'; // And let's stub out everything that's missing! export const ViewPropTypes = { style: () => {}, }; RNText.propTypes = { style: () => {}, }; RNImage.propTypes = { style: () => {}, source: () => {}, }; export const Text = RNText; export const Image = RNImage; // export const ToolbarAndroid = {}; export const requireNativeComponent = () => {};
Now yous can only run react-app-rewired commencement
instead of react-scripts showtime
@flyskywhy thanks a lot, this saved me a twenty-four hour period 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 immune.
"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 Babel doesn't care for the presence of module.exports
(and the absence of import/export statements) as a signal that the file should exist parsed every bit "script" instead, to avoid throwing this error.
Source: https://bleepcoder.com/webpack/201799135/cannot-assign-to-read-only-property-exports-of-object-object
0 Response to "Unhandled Rejection (Typeerror): Cannot Assign to Read Only Property 'exports' of Object '#<object>'"
Postar um comentário