Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug] Console error: Uncaught TypeError: Cannot set properties of undefined (setting 'default') #14628

Closed
1 task done
gongshun opened this issue Jun 1, 2022 · 40 comments · Fixed by #14708
Closed
1 task done
Labels
i: question i: third party The report is a problem of third party outdated A closed issue/PR that is archived due to age. Recommended to make a new issue

Comments

@gongshun
Copy link

gongshun commented Jun 1, 2022

💻

  • Would you like to work on a fix?

How are you using Babel?

Other (Next.js, Gatsby, vue-cli, ...)

Input code

same as https://ask.dcloud.net.cn/question/145538.

I wrote async/await in the project created by vue-cli v4.5.17

Configuration file name

babel.config.json

Configuration

No response

Current and expected behavior

Console error: Uncaught TypeError: Cannot set properties of undefined (setting 'default'),Then I click on the error to view the source code,I saw the code below:

// node_modules/@babel/runtime/helpers/esm/regeneratorRuntime.js 
_regeneratorRuntime = function _regeneratorRuntime() {
    return exports;
};
QQ20220601-163039-HD.mp4

Environment

System:
OS: macOS 12.4
Binaries:
Node: 10.24.1 - ~/.nvm/versions/node/v10.24.1/bin/node
Yarn: 1.22.18 - ~/.nvm/versions/node/v10.24.1/bin/yarn
npm: 6.14.12 - ~/.nvm/versions/node/v10.24.1/bin/npm
npmPackages:
@babel/plugin-transform-modules-commonjs: ^7.7.5 => 7.18.2
babel-eslint: ^10.1.0 => 10.1.0
babel-plugin-import: 1.13.3 => 1.13.3
eslint: ^6.7.2 => 6.8.0

Possible solution

When I moved the code that reported the error below, it worked fine,like this:

// node_modules/@babel/runtime/helpers/esm/regeneratorRuntime.js 
 var exports = {},
      Op = Object.prototype,
      hasOwn = Op.hasOwnProperty,
      $Symbol = "function" == typeof Symbol ? Symbol : {},
      iteratorSymbol = $Symbol.iterator || "@@iterator",
      asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
      toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";

_regeneratorRuntime = function _regeneratorRuntime() {
     return exports;
};
QQ20220601-163301-HD.mp4

Additional context

it works normally when I use @babel/runtime v7.17.9

@babel-bot
Copy link
Collaborator

Hey @gongshun! We really appreciate you taking the time to report an issue. The collaborators on this project attempt to help as many people as possible, but we're a limited number of volunteers, so it's possible this won't be addressed swiftly.

If you need any help, or just have general Babel or JavaScript questions, we have a vibrant Slack community that typically always has someone willing to help. You can sign-up here for an invite.

@Annshuk
Copy link

Annshuk commented Jun 1, 2022

same issue with React project, got the excat same issue with @babel/runtime 7.18.3

@Annshuk
Copy link

Annshuk commented Jun 1, 2022

System:
OS: window 10
Binaries:
Node: 16.13.2
Yarn: 1.22.18
npm: 8.10.0
npmPackages:
@babel/plugin-transform-modules-commonjs: ^7.7.5 => 7.18.2
babel-eslint: ^10.1.0 => 10.1.0
babel-plugin-import: 1.13.3 => 1.13.3
eslint: ^6.7.2 => 8.2

using lerna with rollup

possible solution would be, if we can check first and then assign would be work

// node_modules/@babel/runtime/helpers/esm/regeneratorRuntime.js 
 var exports = exports || {}
_regeneratorRuntime = function _regeneratorRuntime() {
     return exports;
};

var Op = Object.prototype,
      hasOwn = Op.hasOwnProperty,
      $Symbol = "function" == typeof Symbol ? Symbol : {},
      iteratorSymbol = $Symbol.iterator || "@@iterator",
      asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
      toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";


@nicolo-ribaudo
Copy link
Member

I'm really confused by this error. function _regeneratorRuntime() { return exports; } is never called during the execution of the "outer" _regeneratorRuntime function, so at that point exports should be already defined.

Could you open your bundle and check the source of the (outer) _regeneratorRuntime function? If it's minified, you can probably find it by looking for the "@@asyncIterator" string

@Annshuk
Copy link

Annshuk commented Jun 1, 2022

so i am, but the function is calling before excution and getting undfined default value error.

@nicolo-ribaudo
Copy link
Member

Can you share your bundle? I don't understand how function _regeneratorRuntime() { return exports; } can be called before that the subsequent code has been executed.

@Annshuk
Copy link

Annshuk commented Jun 1, 2022

it is looking into esm ->
image

is should be minified or is it not correctly picking up?

@nicolo-ribaudo
Copy link
Member

nicolo-ribaudo commented Jun 1, 2022

Are you bundling your app?

That code contained in @babel/runtime/helpers/esm/regeneratorRuntime.js never calls the function _regeneratorRutime() { return exports } function before defining var exports = {}, so the problem arises after a transform that is applied to that file by your build process (a bundler, or a minifier, or something else).

You need to find the _regeneratorRuntime code in the bundle that you then serve to the browser, to see how it has been transformed.

EDIT: I see that you said that you are using rollup. You need to look at the file generated by rollup.

@Annshuk
Copy link

Annshuk commented Jun 1, 2022

so the config is as below

import babel from "@rollup/plugin-babel";
import { nodeResolve } from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import image from "@rollup/plugin-image";
import { terser } from "rollup-plugin-terser";

import pkg from "./package.json";

const dependencies = [
  ...Object.keys(pkg.peerDependencies),
  ...Object.keys(pkg.devDependencies),
];

export default {
  input: "src/index.js",
  output: [
    { file: pkg.main, format: "cjs", sourcemap: true },
    { file: pkg.module, format: "esm", sourcemap: true },
  ],
  plugins: [
    nodeResolve({
      extensions: [".js", ".ts", ".tsx"],
    }),
    commonjs(),
    babel({
      babelHelpers: "bundled",
      exclude: "node_modules/**",
    }),
    image(),
    terser(),
  ],
  external: [...dependencies],
};

@nicolo-ribaudo
Copy link
Member

You need to check the contents of the file specified in "main": in your package.json.

@Annshuk
Copy link

Annshuk commented Jun 1, 2022

so it is generating like this, so here no export is defined, that means it export default would be undefined

image

@nicolo-ribaudo
Copy link
Member

Yes, it's defined at line 18 in your screenshot.

Could you try disabling source maps, and check what code in that bundled file is throwing exactly?

@Annshuk
Copy link

Annshuk commented Jun 1, 2022

no, you dint understand my point, somehow while testing our application jest is throughing error Uncaught TypeError: Cannot set properties of undefined (setting 'default'), so how it can be excuted that time even not calling that function

@nicolo-ribaudo
Copy link
Member

But that code is not trying to set any property named default, so the error is probably pointing to the wrong location. If you disable source maps, we can see the correct location where something is trying to set a .default property.

@Annshuk
Copy link

Annshuk commented Jun 1, 2022

so do u means that it correct , as here m also not able to c efault, as what i can see in prevsiouly

image
image

@nicolo-ribaudo
Copy link
Member

Yes, that code looks correct. We need to understand what code is throwing about default, because the source maps are pointing at the wrong code.

Would you be able to push a repository that reproduces the bug?

@Annshuk
Copy link

Annshuk commented Jun 1, 2022

so as per above, seems missing with some configuration which is not correctly building. Thanks you very much to pointing this out

@nicolo-ribaudo
Copy link
Member

Could you try removing sourcemap: true from your rollup config (both of them), rebuilding your project, and share the stack trace?

@Annshuk
Copy link

Annshuk commented Jun 1, 2022

also one thing notice, if using babelHelper: runtime, that time it making an issue
so it importing from esm

var _regeneratorRuntime = require('@babel/runtime/helpers/esm/regeneratorRuntime')`

could this be the issue, because it not shown in the building as like below.

image

import babel from "@rollup/plugin-babel";
import { nodeResolve } from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import image from "@rollup/plugin-image";
import replace from "@rollup/plugin-replace";
import { terser } from "rollup-plugin-terser";

import pkg from "./package.json";

const dependencies = [
  ...Object.keys(pkg.peerDependencies),
  ...Object.keys(pkg.devDependencies),
];

export default {
  input: "src/index.js",
  output: [
    { file: pkg.main, format: "cjs" },
    { file: pkg.module, format: "esm" },
  ],
  plugins: [
    replace({ exclude: "node_modules/**", preventAssignment: true }),
    nodeResolve(),
    babel({
      babelHelpers: "bundled",
      exclude: "node_modules/**",
    }),
    commonjs(),
    image(),
    //  terser(),
  ],
  external: [...dependencies],
};


//babelrc

{
    "presets": ["@babel/preset-env", "@babel/preset-react"],
    "env": {
      "test": {
        "presets": [
          ["@babel/preset-env", { "modules": "cjs" }]
        ]
      },
      "build": {
         "presets": [
            ["@babel/preset-env", { "modules": false }]
          ]
       }
    },
    "plugins": [[
      "babel-plugin-module-resolver",
      {
        "root": [
          "./src"
        ]
      }
    ]]
  }

https://github.com/Annshuk/microfrotend-lerna/tree/main/packages/design-system/dist <- can refer this

@gongshun
Copy link
Author

gongshun commented Jun 2, 2022

After I build it becomes like this :
image

@nicolo-ribaudo
Copy link
Member

nicolo-ribaudo commented Jun 3, 2022

@gongshun Thanks, that screenshot is definitely buggy code! However, that is not the code published by us in @babel/runtime, as you already noticed: that e.default = assignment is injected by something else (webpack? rollup? I don't know what bundler vue-cli uses). I suggest reporting this bug to them so that they can fix it 🙏

@Annshuk How can I use your repository to see this bug? I tried running the following commands:

  • yarn in the monorepo root
  • yarn build in packages/design-system
  • yarn test in packages/design-system

but all the tests passed without errors. I also tried yarn storybook (after fixing the Button import in packages/design-system/src/components/Button/Button.stories.js), and even aftrer clicking on the button in the browser a few times I still don't see the error.

@Annshuk
Copy link

Annshuk commented Jun 3, 2022

The problems is with different system with same configuratio, so there when bundles creating it taking from
var _regeneratorRuntime = require('@babel/runtime/helpers/esm/regeneratorRuntime')
which i dont wana, how can i use
var _regeneratorRuntime = require('@babel/runtime/helpers/regeneratorRuntime') `

all the errors is happening while running test, so it throwing that regeneratorRuntime error

@nicolo-ribaudo any Suggestion or is this issue.

@liuxingbaoyu liuxingbaoyu added i: question i: third party The report is a problem of third party and removed i: needs triage labels Jun 3, 2022
@nicolo-ribaudo
Copy link
Member

@Annshuk I'll need a repository I can use to reproduce the bug. Unfortunately I ran out of ideas for this, I don't know what is causing the error 😅

@gongshun
Copy link
Author

gongshun commented Jun 6, 2022

@nicolo-ribaudo it works normally when I use @babel/runtime v7.17.9

@Annshuk
Copy link

Annshuk commented Jun 8, 2022

@nicolo-ribaudo thought my bundler cjs having var _regeneratorRuntime = require('@babel/runtime/helpers/esm/regeneratorRuntime') which i am expecting to be var _regeneratorRuntime = require('@babel/runtime/regeneratorRuntime')` so not sure why it budle in cjs

@DevSysEngineer
Copy link

I have exactly the same issue as the issue starter. The given solution is also working on our side. The variable exports can not be found and when this function will call we got this strange error.

@nicolo-ribaudo
Copy link
Member

@KvanSteijn Can you provide a repository I can clone to reproduce the problem? It's imposble for us to understand what's causing the bug otherwise.

@DevSysEngineer
Copy link

@nicolo-ribaudo we are using React Dropdown (https://github.com/react-component/dropdown), this package used multiple other packages. One of this packages is rc-trigger. When we are compiling our code, async (https://github.com/react-component/trigger/blob/f5fb0e980698a97fce0e531a78087fc8a38b4757/src/Popup/useVisibleStatus.ts#L86 )will be transformed to _regeratorRuntime. But it's look like that this function is broken after couple of modifications.

image

2022-06-17 13 20 07

@nicolo-ribaudo
Copy link
Member

I'm sorry but I will need a repository. This bug is probably caused by a specific combination of different tools (Babel, webpack, terser maybe? Or other bundlers/minifiers), and without seeing how they are interacting I cannot guess what's happened.

@codeHessel
Copy link

sameproblem,is there any solution to fix it? @nicolo-ribaudo

@codeHessel
Copy link

I have found something, when I change the code from "async await" to a Promise, it work! so, does the babel 's update have an influence on es6 compiling?
image
image
image

@nicolo-ribaudo
Copy link
Member

Can you provide a repository I can clone to reproduce the problem? It's imposble for us to understand what's causing the bug otherwise.

@nicolo-ribaudo
Copy link
Member

Note: from the screenshots and stack traces its clear that this is almost certainly not a Babel bug. There is some tool that you are all using that incorrectly rewrites exports.default in that Babel helper. The reason you are seeing this error after a Babel update is because we had to change the contents of that helper.

I'm being nice and offering to help all of you for free by cloning a repository that reproduces the bug, debug it and find which tool is broken, so that we can report the bug in the correct place. However, if none of you can provide such demo that shows the bug (and I now asked for or 4 times) I'm going to close this issue and you all will have to figure out which tool is transforming the helper code incorrectly by yourself.

@nicolo-ribaudo
Copy link
Member

Ok, lets try to make things simpler. @codeHung shows almost certainly that it's a webpack bug. Which webpack version are you using?

@MuppetPower
Copy link

@nicolo-ribaudo I have the same issue (I don't have repository I can share unfortunately). My Webpack is at version 4.4.6 if that helps - for some other reasons I'm blocked in using Webpack 5 for the time being, so its the latest 4.x I'm using.

Thanks for taking the time to help us with this!

@nicolo-ribaudo
Copy link
Member

nicolo-ribaudo commented Jun 29, 2022

Ohh maybe I have an idea. I found a similar Babel bug, but it shouldn't affect you if you are using babel-loader (i.e. Babel in webpack) or #14628 (comment).

However, I'll fix it and maybe it will solve this problem. It could only affect you if you are using Babel to compile ESM to CJS in webpack (you shouldn't! Webpack prefers ESM to CommonJS) and you are compiling your dependencies.

@MuppetPower
Copy link

MuppetPower commented Jun 29, 2022

I'll confess to not fully understanding what you said, but perhaps this config from my webpack is relevant if by CJS you mean corejs?

const babelLoader = {
		loader: 'babel-loader',
		options: {
			presets: [['@babel/preset-env', { useBuiltIns: 'entry', corejs: 3 }]],
			compact: false,
			plugins: [
				'@babel/plugin-transform-async-to-generator',
				'@babel/plugin-transform-arrow-functions',
				'@babel/plugin-transform-modules-commonjs',
				['inline-dotenv', { path: `.env.${argv.mode}`, unsafe: true }],
				['import', { libraryName: 'antd', style: true }],
			],
		},
	};

@nicolo-ribaudo
Copy link
Member

nicolo-ribaudo commented Jun 29, 2022

Sorry, CommonJS.

If you delete @babel/plugin-transform-modules-commonjs, this bug should disappear (if my intuition is correct) and you should get a lightly smaller webpack output.

Btw, is there any reason why you enabled @babel/plugin-transform-async-to-generator and @babel/plugin-transform-arrow-functions? They are already included in @babel/preset-env.

@nicolo-ribaudo
Copy link
Member

I opened #14708 which might hopefully fix this. Babel was broken when compiling a specific exoprts combination at least since Babel 7.0.0, but the problem now is that @babel/runtime is using that specific combination 😅

For most of you, the best solution is to not transform CommonJS modules when using Rollup or Webpack, since bundlers can optimize your code better when they see the original ESM code.

@MuppetPower
Copy link

Sorry, CommonJS.

If you delete @babel/plugin-transform-modules-commonjs, this bug should disappear (if my intuition is correct) and you should get a lightly smaller webpack output.

Btw, is there any reason why you enabled @babel/plugin-transform-async-to-generator and @babel/plugin-transform-arrow-functions? They are already included in @babel/preset-env.

Thanks so much - this fixed the issue for me.

I inherited the project so perhaps they didn't used to part of @babel/preset-env - I'll remove them now.

@github-actions github-actions bot added the outdated A closed issue/PR that is archived due to age. Recommended to make a new issue label Sep 29, 2022
@github-actions github-actions bot locked as resolved and limited conversation to collaborators Sep 29, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
i: question i: third party The report is a problem of third party outdated A closed issue/PR that is archived due to age. Recommended to make a new issue
Projects
None yet
Development

Successfully merging a pull request may close this issue.

8 participants