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] Cannot read property 'add' of undefined #556

Closed
louisgv opened this issue May 24, 2017 · 54 comments
Closed

[BUG] Cannot read property 'add' of undefined #556

louisgv opened this issue May 24, 2017 · 54 comments
Labels
bug Confirmed bug with es2015 The bug is caused when used with es2015-block-scoping plugin

Comments

@louisgv
Copy link

louisgv commented May 24, 2017

Here's my .babelrc:

babelrc
{
  "presets": [
    "es2015", "stage-2", "stage-0", "react", "es2015-ie"
  ],
  "plugins": [
    "transform-runtime", "transform-decorators-legacy", "transform-class-properties"
  ],
  "compact": true,
  "env": {
    "test": {
      "plugins": ["istanbul"]
    },
    "production": {
      "presets": [
         "babili"
      ]
    }
  }
}

Running babel resulted in this error:

ERROR in ./src/components/Main/index.js
Module build failed: TypeError: /src/components/Main/index.js: Cannot read property 'add' of undefined
    at ScopeTracker.addReference (/node_modules/babel-plugin-minify-mangle-names/lib/scope-tracker.js:55:36)
    at ReferencedIdentifier (/node_modules/babel-plugin-minify-mangle-names/lib/index.js:190:28)
    at newFn (/node_modules/babel-traverse/lib/visitors.js:318:17)
    at bfsTraverse (/node_modules/babel-plugin-minify-mangle-names/lib/bfs-traverse.js:34:43)
    at Mangler.collect (/node_modules/babel-plugin-minify-mangle-names/lib/index.js:269:9)
    at Mangler.run (/node_modules/babel-plugin-minify-mangle-names/lib/index.js:70:14)
    at PluginPass.exit (/node_modules/babel-plugin-minify-mangle-names/lib/index.js:589:19)
    at newFn (/node_modules/babel-traverse/lib/visitors.js:276:21)
    at NodePath._call (/node_modules/babel-traverse/lib/path/context.js:76:18)
    at NodePath.call (/node_modules/babel-traverse/lib/path/context.js:48:17)
    at NodePath.visit (/node_modules/babel-traverse/lib/path/context.js:117:8)
    at TraversalContext.visitQueue (/node_modules/babel-traverse/lib/context.js:150:16)
    at TraversalContext.visitSingle (/node_modules/babel-traverse/lib/context.js:108:19)
    at TraversalContext.visit (/node_modules/babel-traverse/lib/context.js:192:19)
    at Function.traverse.node (/node_modules/babel-traverse/lib/index.js:114:17)
    at traverse (/node_modules/babel-traverse/lib/index.js:79:12)
    at File.transform (/node_modules/babel-core/lib/transformation/file/index.js:548:35)
    at /node_modules/babel-core/lib/transformation/pipeline.js:50:19
    at File.wrap (/node_modules/babel-core/lib/transformation/file/index.js:564:16)
    at Pipeline.transform (/node_modules/babel-core/lib/transformation/pipeline.js:47:17)
    at transpile (/node_modules/babel-loader/lib/index.js:46:20)
    at Object.module.exports (/node_modules/babel-loader/lib/index.js:163:20)
 @ ./src/dist.js 1:127-153

Now if I disable Mangling, the minification doesn't seem to have much effect:

npm run dist

> BABEL_ENV=production webpack --env=dist

Hash: b6d52d6cc9478801536d
Version: webpack 1.15.0
Time: 4355ms
               Asset    Size  Chunks             Chunk Names
    dist.js  749 kB       0  [emitted]  main
dist.js.map  923 kB       0  [emitted]  main
    + 340 hidden modules

Dist without production env:

> webpack --env=dist

Hash: 8636992c125a9a4e5f8a
Version: webpack 1.15.0
Time: 3934ms
               Asset    Size  Chunks             Chunk Names
    dist.js  752 kB       0  [emitted]  main
    dist.js.map  925 kB       0  [emitted]  main
    + 340 hidden modules
@boopathi boopathi added the bug Confirmed bug label May 24, 2017
@boopathi
Copy link
Member

boopathi commented May 24, 2017

Thanks. Do you have a minimal reproduction code snippet or the input code that creates this error ?

And since you're using webpack, can you try with babili-webpack-plugin to find if the same error happens with babili webpack plugin.

There are a few issues when used with es2015

@joewilson81
Copy link

I was having the same issue today, but I'm not using webpack.

It was working before some changes I had made, so I stashed them and re-applied them one by one. The culprit was the snippet below in a function that otherwise had no return value:

if (!someLocalBooleanVariable && this.state.anotherBooleanVariable) {
      return;
}

I can't show the client's code, but I'll try to put together an example later and see if I can reproduce the issue.

@louisgv louisgv changed the title [SUPPORT] Cannot read property 'add' of undefined [Bug] Cannot read property 'add' of undefined May 29, 2017
@louisgv louisgv changed the title [Bug] Cannot read property 'add' of undefined [BUG] Cannot read property 'add' of undefined May 29, 2017
@craftzdog
Copy link

I got same error with following code:

import { app } from 'electron'

app.session = {
  async start () {
    await app.windowManager.createFullWindow({})
  }
}

Making alias of app resolved the error:

import { app } from 'electron'

const app2 = app

app.session = {
  async start () {
    await app2.windowManager.createFullWindow({})
  }
}

Hope it helps.

@boopathi
Copy link
Member

Is everyone here facing this issue ONLY when using babili and es2015-block-scoping in the same transformation (or) both in babelrc ? (es2015-block-scoping is included in preset-es2015 or preset-env with a browser setting that converts let/const to var.)

Is anyone getting the same bug when used WITHOUT es2015-block-scoping ?

@craftzdog
Copy link

@boopathi

My .babelrc is:

{
  "presets": [
    "stage-0",
    ["env", {
      "targets": {
        "node": "7.4.0",
        "electron": "1.6.7"
      },
      "useBuiltIns": true
    }]
  ],
  "plugins": [
    "add-module-exports",
    "transform-decorators-legacy"
  ],
  "env": {
    "production": {
      "presets": ["babili"]
    }
  }
}

When I removed preset-env, it worked.
But below config with transform-es2015-block-scoping also worked:

{
  "presets": [
    "stage-0"
  ],
  "plugins": [
    "transform-es2015-block-scoping",
    "add-module-exports",
    "transform-decorators-legacy"
  ],
  "env": {
    "production": {
      "presets": ["babili"]
    }
  }
}

@OR13
Copy link

OR13 commented Jun 7, 2017

I am also experiencing this issue. My .babelrc

{
  "plugins": ["transform-runtime", "lodash", "transform-decorators-legacy"],
  "presets": ["es2015", "react", "stage-0", "babili"]
}

I can resolve it by turning mangle off:

{
  "plugins": [
    "transform-runtime",
    "lodash",
    "transform-decorators-legacy"
  ],
  "presets": [
    "es2015",
    "react",
    "stage-0",
    [
      "babili",
      {
        "evaluate": false,
        "mangle": false
      }
    ]
  ]
}

@jfurfaro
Copy link

jfurfaro commented Jun 8, 2017

I'm also having the issue, but only when transforming my source files with browserify. The second call to babili in gulp-babel doesn't error. Trying babili only in the browserify transform still errors. If I just disable mangle in the browserify transform, it works.

My gulp task

gulp.task('scripts', () => {
	const b = browserify({
		entries: 'source/app.js',
		debug: false,
		paths: ['source/'],
		transform: [
			[
				'babelify', {
					presets: ['es2017', 'react', 'babili'], // es6 minify on the way in
					plugins: ['transform-es2015-modules-commonjs', 'transform-object-rest-spread']
				}
			]
		]
	});

	return b.bundle().on('error', handleError)
		.pipe(source('app.js'))
		.pipe(buffer())
		.pipe(babel({presets: ['babili']})) // es6 minify the whole bundle on the way out
		.pipe(gulp.dest('dist/'));
});

@boopathi boopathi added the with es2015 The bug is caused when used with es2015-block-scoping plugin label Jun 8, 2017
domtronn added a commit to uswitch/ustyle-react that referenced this issue Jun 9, 2017
I tried to use a couple of things integrated directly with babel,

+ https:/babel/babili - Issue with es2015 preset babel/minify#556
+ https:/rreverser/babel-plugin-uglify - Just didn't work!

So, added in a script using the UglifyJS2 CLI tool which saves ~20% of
the size! ✌
@arichiardi
Copy link

So I have a repro repo: https:/arichiardi/js.spec/tree/webpack-babili 😄

Just run yarn and yarn run build

@alcuadrado
Copy link

I'm having this same issue with this .babelrc:

{
  "presets": [
    [
      "env",
      {
        "targets": {
          "chrome": 55
        }
      }
    ],
    "react",
    "babili"
  ],
  "plugins": [
    "transform-object-rest-spread"
  ]
}

@jrencz
Copy link

jrencz commented Jul 11, 2017

I'm having the same issue. In my case it happens when there's a class and at least one method name is a symbol. If I switch from symbol to string (either computed or not) it works fine:

Fails:

const someSymbol = Symbol('meant to keep method private-ish. not to be exported or exposed any other way');

export default class Foo {
   [someSymbol]() {}
}

Works:

export default class Foo {
   some() {}
}

Using: 0.1.3 (latest currently)

.babelrc
{
  "presets": [
    "latest",
    "stage-0",
    "babili",
  ],
  "plugins": [
    "babel-plugin-add-module-exports"
  ]
}

@gajus
Copy link

gajus commented Jul 19, 2017

Same issue with mangle on.

The following code is output of Babili. Here tokens is undefined causing an error.

function(t) {
    for (var a = /<em>(.*?)<\/em>/, n = t, i = [], d = 0; n.length; ) {
        d++;
        var l = n.match(a);
        if (l) {
            var r = l.index;
            0 !== r && i.push(n.slice(0, r));
            var s = l[0];
            i.push(Fa["default"].createElement("em", {
                key: d
            }, s.slice(4, -5))),
            n = n.slice(r + s.length)
        } else {
            i.push(n);
            break
        }
    }
    return tokens
}

Here is the input code:

const createReactElement = (name: string): $ReadOnlyArray<string | React$Element<*>> => {
  const rule = /<em>(.*?)<\/em>/;

  let tail = name;

  const tokens = [];

  let index = 0;

  while (tail.length) {
    index++;

    const match = tail.match(rule);

    if (match) {
      // $FlowFixMe
      const matchIndex = match.index;

      if (matchIndex !== 0) {
        tokens.push(tail.slice(0, matchIndex));
      }

      const matchingString = match[0];

      tokens.push(<em key={index}>{matchingString.slice(4, -5)}</em>);

      tail = tail.slice(matchIndex + matchingString.length);
    } else {
      tokens.push(tail);

      break;
    }
  }

  return tokens;
};

@not-an-aardvark
Copy link
Member

I'm looking into fixing this. I've narrowed it down to a very small reproducible example:

import Foo from 'bar';
class Baz extends Foo {}
(function() { Foo }), Baz;
{
  "plugins": ["transform-es2015-modules-commonjs", "minify-mangle-names"]
}

The issue doesn't seem to occur if the order of the plugins is flipped, or if one plugin is run on the output of the other. The two plugins might be conflicting with each other somehow.

@jmahc
Copy link

jmahc commented Aug 3, 2017

@not-an-aardvark Doing the same - funny I saw your post load as I was visiting this page!

TODO - edit this post with current .babelrc and (potential) fix.

@not-an-aardvark
Copy link
Member

I think I figured out the issue -- it seems like it's actually a problem with babel-plugin-transform-es2015-modules-commonjs. Working on a PR to babel/babel now.

@julienvincent
Copy link

After upgrading babel to latest version I am still experiencing this issue

@jtraulle
Copy link

I am also affected with preset "env". Any progress on this ?
I have tried babel/babel 7.0.0-alpha.19 with babel/babel#6054 merged but now got a

Cannot read property 'bindings' of null

@icopp
Copy link

icopp commented Sep 13, 2017

I'm experiencing the same as @julienvincent and @jtraulle.

@JamesLMilner
Copy link

JamesLMilner commented Sep 13, 2017

Thanks for the package. I am also experiencing this issue with the latest version. Here is an example error log:

ERROR in ./node_modules/ol/events/eventtarget.js
Module build failed: TypeError: /home/james/Code/mapbox-to-ol-style/node_modules/ol/events/eventtarget.js: Cannot read property 'add' of undefined
    at ScopeTracker.addReference (/home/james/Code/mapbox-to-ol-style/node_modules/babel-plugin-minify-mangle-names/lib/scope-tracker.js:55:36)
    at ReferencedIdentifier (/home/james/Code/mapbox-to-ol-style/node_modules/babel-plugin-minify-mangle-names/lib/index.js:190:28)
    at newFn (/home/james/Code/mapbox-to-ol-style/node_modules/babel-traverse/lib/visitors.js:318:17)
    at bfsTraverse (/home/james/Code/mapbox-to-ol-style/node_modules/babel-plugin-minify-mangle-names/lib/bfs-traverse.js:34:43)
    at Mangler.collect (/home/james/Code/mapbox-to-ol-style/node_modules/babel-plugin-minify-mangle-names/lib/index.js:269:9)
    at Mangler.run (/home/james/Code/mapbox-to-ol-style/node_modules/babel-plugin-minify-mangle-names/lib/index.js:70:14)
    at PluginPass.exit (/home/james/Code/mapbox-to-ol-style/node_modules/babel-plugin-minify-mangle-names/lib/index.js:589:19)
    at newFn (/home/james/Code/mapbox-to-ol-style/node_modules/babel-traverse/lib/visitors.js:276:21)
    at NodePath._call (/home/james/Code/mapbox-to-ol-style/node_modules/babel-traverse/lib/path/context.js:76:18)
    at NodePath.call (/home/james/Code/mapbox-to-ol-style/node_modules/babel-traverse/lib/path/context.js:48:17)
    at NodePath.visit (/home/james/Code/mapbox-to-ol-style/node_modules/babel-traverse/lib/path/context.js:117:8)
    at TraversalContext.visitQueue (/home/james/Code/mapbox-to-ol-style/node_modules/babel-traverse/lib/context.js:150:16)
    at TraversalContext.visitSingle (/home/james/Code/mapbox-to-ol-style/node_modules/babel-traverse/lib/context.js:108:19)
    at TraversalContext.visit (/home/james/Code/mapbox-to-ol-style/node_modules/babel-traverse/lib/context.js:192:19)
    at Function.traverse.node (/home/james/Code/mapbox-to-ol-style/node_modules/babel-traverse/lib/index.js:114:17)
    at traverse (/home/james/Code/mapbox-to-ol-style/node_modules/babel-traverse/lib/index.js:79:12)
    at File.transform (/home/james/Code/mapbox-to-ol-style/node_modules/babel-core/lib/transformation/file/index.js:548:35)
    at /home/james/Code/mapbox-to-ol-style/node_modules/babel-core/lib/transformation/pipeline.js:50:19
    at File.wrap (/home/james/Code/mapbox-to-ol-style/node_modules/babel-core/lib/transformation/file/index.js:564:16)
    at Pipeline.transform (/home/james/Code/mapbox-to-ol-style/node_modules/babel-core/lib/transformation/pipeline.js:47:17)
    at transpile (/home/james/Code/mapbox-to-ol-style/node_modules/babel-loader/lib/index.js:50:20)
    at Object.module.exports (/home/james/Code/mapbox-to-ol-style/node_modules/babel-loader/lib/index.js:175:20)
 @ ./node_modules/ol/observable.js 1:219-250
 @ ./node_modules/ol/object.js
 @ ./node_modules/ol/feature.js
 @ ./test/test.js

Let me know if there's anything I can do to help.

@derwaldgeist
Copy link

derwaldgeist commented Oct 29, 2017

Thanks, setting mangle to false works for me, too. But I need name mangling, for size reduction as well as for code obfuscation. Perhaps it's possible to use a separate name mangler plugin somehow?

@WhoAteDaCake
Copy link

I agree with @derwaldgeist Is there any better solution?

@perrosnk
Copy link

Any updates on this?

@282159468
Copy link

Having this problem too.

@llewellyncollins
Copy link

I am also having this problem when mangle is set to true. Is setting it to false the only solution?

@wldcordeiro
Copy link

This issue is closed but the errors are still present, a workaround was found but I don't think it's optimal.

onbjerg added a commit to aragon/aragon.js that referenced this issue Mar 18, 2018
TheXardas added a commit to TheXardas/page-view-counter that referenced this issue Apr 13, 2018
devongovett added a commit to devongovett/minify that referenced this issue May 20, 2018
Fixes "Cannot read property 'add' of undefined" error. babel#792 babel#556
@devongovett
Copy link

Just made a PR to work around the issue: #860. I'm not exactly sure why it happens - I'm not using the commonjs modules transform but it still happens for me. This seems to fix the issue though by just adding the missing scope before trying to track a reference in it.

@LabhanshAgrawal
Copy link

@devongovett This error is occurring again, on updating to babel core 7.8.0

@copyrighthero
Copy link

copyrighthero commented Jan 28, 2020

I'm upgrading babel from 7.7.4 to 7.8.3 today and this happened to me too, after changing the configuration for minify from {mangle: true} to {mangle: false} I was able to build without problem; the name mangling is the issue for me too :-/

@arantes555
Copy link

Same thing here. It seems to be happening again with 7.8, and seems it can be worked-around with {mangle: false}

@eugenmihailescu
Copy link

In my case the same error occurred due to some function's parameter default value set to a constant.

const VALUE = 10;

function myFunction(param = VALUE) {...}

The workaround was to replace the constant in the function declaration, like this:

function myFunction(param = 10) {...}

or

function myFunction(param) {
  if ("undefined" === typeof param) {
      param = VALUE;
  }
}

@somewhatabstract
Copy link

I am seeing this same error when using rollup-babel-minify.

TypeError: unknown: Cannot read property 'add' of undefined
    at ScopeTracker.addReference (/Users/jeffyates/git/checksync/node_modules/babel-plugin-minify-mangle-names/lib/scope-tracker.js:47:34)
    at ReferencedIdentifier (/Users/jeffyates/git/checksync/node_modules/babel-plugin-minify-mangle-names/lib/index.js:196:26)
    at newFn (/Users/jeffyates/git/checksync/node_modules/@babel/traverse/lib/visitors.js:220:17)
    at bfsTraverse (/Users/jeffyates/git/checksync/node_modules/babel-plugin-minify-mangle-names/lib/bfs-traverse.js:32:43)
    at Mangler.collect (/Users/jeffyates/git/checksync/node_modules/babel-plugin-minify-mangle-names/lib/index.js:229:7)
    at Mangler.run (/Users/jeffyates/git/checksync/node_modules/babel-plugin-minify-mangle-names/lib/index.js:54:12)
    at PluginPass.exit (/Users/jeffyates/git/checksync/node_modules/babel-plugin-minify-mangle-names/lib/index.js:558:19)
    at newFn (/Users/jeffyates/git/checksync/node_modules/@babel/traverse/lib/visitors.js:179:21)
    at NodePath._call (/Users/jeffyates/git/checksync/node_modules/@babel/traverse/lib/path/context.js:55:20)
    at NodePath.call (/Users/jeffyates/git/checksync/node_modules/@babel/traverse/lib/path/context.js:42:17)

@ambroselittle
Copy link

This is still a problem today. @eugenmihailescu's workaround worked for me, which suggests that this plugin doesn't handle that correctly, even though it's valid. So it really should be re-opened and fixed (or a new issue).

Anyhow, I switched to terser, since that works for my sitch, and it handles using var/funcs to set default param values just fine.

@cerinoligutom
Copy link

Encountered this today. @eugenmihailescu's workaround worked for me.

My scenario:
I'm using TypeScript and an enum value as the default value for a function parameter.

Did a bit of testing and found out it's not necessarily due to a constant but rather, as long as it's coming from a variable, it'll fail to transform.

@monokee
Copy link

monokee commented Jun 16, 2020

It's still an issue. (rollup-babel-minify)

@dimaqq
Copy link

dimaqq commented Mar 1, 2021

Would it be better to reopen this issue or create new one?

@ChenYCL
Copy link

ChenYCL commented Feb 22, 2022

same tody

banjerluke added a commit to banjerluke/svelte-headlessui that referenced this issue May 4, 2022
Some versions of babel-minify choke on function parameters
that default to named constants:
babel/minify#556
This moves the default assignment into the function body.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Confirmed bug with es2015 The bug is caused when used with es2015-block-scoping plugin
Projects
None yet
Development

No branches or pull requests