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

webpack -p outputs: ERROR in bundle.js from UglifyJs Unexpected token: name (login) [./login.es6:2,4] #3

Closed
MBing opened this issue Nov 11, 2015 · 88 comments

Comments

@MBing
Copy link

MBing commented Nov 11, 2015

I am getting an error when trying to use webpack -p. When I change the code to ES5 compatible code it seems to work. Something with the UglifyJS minification and ES6 apparently.

This is my login.es6 file:

"use strict";
let login = (username, pw) => {
    if (username !== 'admin' || pw !== 'radical') {
        console.log("login incorrect");
    }
};

login("admin", "test");

I have exactly the same code as the course mentions. I am using the newer versions of the tools and it seems to be a problem there. When using the versions as provided in the course, There is also no error when only changing babel-core and babel-loader to the versions provided.

My version of devDependencies (with UglifyJS error):

"devDependencies": {
  "babel-core": "^6.1.4",
  "babel-loader": "^6.1.0",
  "jshint": "^2.8.0",
  "jshint-loader": "^0.8.3",
  "node-libs-browser": "^0.5.3",
  "strip-loader": "^0.1.0",
  "webpack": "^1.12.4"
}

My partially updated version of devDependencies (without UglifyJS error):

"devDependencies": {
  "babel-core": "^5.4.7",
  "babel-loader": "^5.1.3",
  "jshint": "^2.8.0",
  "jshint-loader": "^0.8.3",
  "node-libs-browser": "^0.5.3",
  "strip-loader": "^0.1.0",
  "webpack": "^1.12.4"
}

Does anyone have an idea on how to solve this minification problem while using babel >6?
Thanks!

@gfunk1230
Copy link

@joeeames I am having the same issue here. I getting ERROR in bundle.js from UglifyJs
Unexpected token: name (login) [./login.es6:3,4] Please help here. Thanks

@joeeames
Copy link
Owner

I'll try to take a look at it over the holiday. There was a major release for Babel so that's probably it.

@gfunk1230
Copy link

@joeeames thanks so much and have a Happy Thanksgiving.

@joeeames
Copy link
Owner

Hey, you too! May the pie be never-ending!

@jurrinus
Copy link

Holiday is over Joe. Hope it was great! Now back to the error. I'm getting it also. Will back off to the versions you specified in the course. Cold Hearted Learner. Thanks, Jerry

@jurrinus
Copy link

Backed of babel-core to 5.4.7, babel-loader to 5.1.3 and for safety webpack to 1.12.9 and all worked well. Great course Joe. Moving forward. Jerry

@joeeames
Copy link
Owner

ok, the readme file for this repo has the directions to work correctly around this issue while using the latest version of Babel. Please look at that, let me know if you have any issues. Also, an update has been submitted to the course videos, although it can take as long as a month to get published.

@Friend-LGA
Copy link

+1 UglifyJs in webpack not working with babel >= 6.0.0
Unexpected token: name ...

@danielabar
Copy link

I followed the directions in this repo for Babel 6, but also getting the unexpected token error when running production build. It only happens in the "Organizing Files and Folders" course section, when the javascript files get moved into a js folder. In the previous section when all the js files are in the root directory, the production build runs fine.

Is there any other webpack config required to tell it that the js files are now in a "js" directory?

From the error message, looks like Uglify is trying to process the .es6 file, but should it first be transpiled to js by babel?

Running:

webpack --config webpack-production.config.js -p

And error:

> webpack-pluralsight-lesson-03@1.0.0 prod /Users/dbaron/projects/webpack-pluralsight/lesson-04
> webpack --config webpack-production.config.js -p

Hash: d146267acff6790ea92d
Version: webpack 1.12.9
Time: 484ms
    Asset     Size  Chunks             Chunk Names
bundle.js  2.04 kB       0  [emitted]  main
   [0] multi main 40 bytes {0} [built]
    + 3 hidden modules

WARNING in ./app.js
jshint results in errors
  document.write can be a form of eval. @ line 3 char 1
    document.write('Welcome to Big Hair Concerts!! ignoring jshint error here');

ERROR in bundle.js from UglifyJs
Unexpected token: name (login) [./login.es6:3,4]

@danielabar
Copy link

Update: I noticed that as of the "Organizing Files and Folders" course section, even running the dev build, the es6 files were no longer being transpiled. Updated the loader section slightly to specify "babel" instead of "babel-loader" and added a "query" section for presets. Now both dev and prod builds work:

loaders: [
      {
        test: /\.es6$/,
        exclude: /node_modules/,
        loader: 'babel',
        query: {
          presets: ['es2015']
        }
      }
    ]

@vmadman
Copy link

vmadman commented May 6, 2016

I've ran into a similar problem, but, I'm not using Babel (unless I left a switch set somewhere in some pasted code, but I've checked). Instead, I am posting to a platform that allows ES6 natively via Node 4.3. Any advice on what I could do to correct this?

Unexpected token: name (str) [./handler.js:10,0]

Here' line #10 ..

    let str = "";

@joeeames
Copy link
Owner

Just an update to those following this thread, I will be working through this to see what needs to change in the course, and apologies for the delays, the process takes a long time.

@hopcycle
Copy link

@joeeames I'm currently working through the tutorial; I can mark down any issues I come across and forward them on to you if it would help?

@joeeames
Copy link
Owner

That would be excellent @hopcycle!

@MartinMuzatko
Copy link

Same issue here.

@james-world
Copy link

@danielabar @joeeames When I ran into this, adding just the query option as per danielabar's comment fixed things for me:

    loaders: [
        {
            test: /\.es6$/,
            exclude: /node_modules/,
            loader: "babel-loader",
            query: {
                presets: ["es2015"]
            }
        }
    ]

@rustikov
Copy link

rustikov commented Jun 27, 2016

Thanks @danielabar.

npm install babel --save-dev
npm install babel-preset-es2015 --save-dev

loaders: [  {
    test: /\.js$/,
        loader: 'babel',
        query: {
          presets: ['es2015']
        }
    }
]

@tarun2502
Copy link

tarun2502 commented Jul 2, 2016

Still not working for me , done the above points
Finally worked, was a error.

@mjt60
Copy link

mjt60 commented Jul 14, 2016

+1 for @danielabar's solution.

@brunobritodev
Copy link

brunobritodev commented Aug 24, 2016

I was with same problem, but I'm using typescript with es6 and ts-loader.

// tsconfig.json
{
  "compilerOptions": {
    "target": "es6"
  },
  "files": [...]
}

And changed loader like this:

// webpack.config.js
module.exports = {  
  ...
  module: {
    loaders: [
      // note that babel-loader is configured to run after ts-loader
      { test: /\.ts(x?)$/, loader: 'babel-loader!ts-loader' }
    ]
  }
}

Courtesy from http://www.jbrantly.com/es6-modules-with-typescript-and-webpack/

Hope that help someone with same problem!

@bogusfocused
Copy link

I have the same error in webpack 2 with typescript 2

@LanderBeeuwsaert
Copy link

Same here: webpack 2, typescript 2

@kesarion
Copy link

@Rohitlodha @LanderBeeuwsaert

For typescript, I recommend using npm i awesome-typescript-loader babel-loader babel-core --save-dev with the following rule:

rules: [
        {
            test: /\.ts$/,
            loaders: [
                'babel-loader?presets[]=es2015',
                'awesome-typescript-loader',
                // For angular2:
                //'angular2-template-loader',
                //`angular2-router-loader?genDir=compiled/app&aot=true`
            ],
            exclude: [/\.(spec|e2e|d)\.ts$/]
        }
]

and tsconfig:

{
  "compilerOptions": {
    "target": "es6",
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "noEmitHelpers": true,
    "skipDefaultLibCheck": true,
    "strictNullChecks": false,
    "outDir": "tmp"
  },
  "exclude": [
    "node_modules"
  ],
  "awesomeTypescriptLoaderOptions": {
    "useBabel": true,
    "useCache": true
  }
}

@fulls1z3
Copy link

webpack#2 users, I can also suggest an alternative solution who wants to stick to ES6 (by implication to prevent to transpile code on every build, and ofc prevent loading ES6 polyfills).below are detailed instructions to use the Harmony branch of UglifyJs2 with webpack:

  • Fork webpack,
  • On that fork, delete all branches except master,
  • Clone master branch to a local folder,
  • On the local folder, delete all files,
  • Commit the empty local folder,
  • Download the latest release (ex: v2.1.0-beta.27 at the moment)
  • Extract contents of zip file to the local folder,
  • On the local folder, edit forked package.json, change
"uglify-js": "git+https://github.com/mishoo/UglifyJS2.git#harmony"

to point UglifyJs2 (harmony branch) dependency to that branch.

  • Commit changes,
  • Finally, point webpack in your package.json to your custom fork:
"webpack": "[USERNAME]/webpack#master"

OR,

  • Point webpack in your package.json to fulls1z3/webpack (ES6/ES2015 friendly webpack fork):
"webpack": "fulls1z3/webpack#v2.1.0-beta.27-harmony"

@Ch4s3
Copy link

Ch4s3 commented Nov 28, 2016

@fulls1z3 That doesn't seem to fix it for me.
I get an error on this code:

const parseSVG = function parseSVG(svg, width, height) {
  let div = document.createElementNS('http://www.w3.org/1999/xhtml', 'div')
  div.innerHTML = '<svg width="'+width+'" height="'+height+'">'+svg+'</svg>'
  return div.firstChild;
}

Specifically:
let div = document.createElementNS('http://www.w3.org/1999/xhtml', 'div')

Gives me the following output

== Executing: `./node_modules/webpack/bin/webpack.js --bail -p`
== External: Hash: a2d4637a403797466795
== External: Version: webpack 2.1.0-beta.27
== External: Time: 105ms
== External:     Asset     Size  Chunks             Chunk Names
== External: bundle.js  4.33 kB       0  [emitted]  main
== External:    [0] ./source/javascripts/all.js 1.9 kB {0} [built]
== External: ERROR in bundle.js from UglifyJs
== External: SyntaxError: Unexpected token: name (div) [bundle.js:73,7]
== External: Command failed with non-zero exit status

When I run ./node_modules/webpack/bin/webpack.js --bail -p"
With both "webpack": "2.1.0-beta.27" and "webpack": "fulls1z3/webpack#v2.1.0-beta.27-harmony"

@dcartertwo
Copy link

dcartertwo commented Dec 17, 2016

+1 seeing this issue. using webpack 2, babel 6

ERROR in empmap/empmap.bundle.js from UglifyJs
SyntaxError: Unexpected character '`' [./plugins/empmap/ui/module.js:17,0]

relevant webpack config:

module: {
    loaders: [
      {
        test: /\.js$/,
        include: JS_INCLUDES,
        loader: 'babel-loader',
        cacheDirectory: true,
        query:{
          presets: ['es2015'],
          plugins: ["transform-es2015-template-literals"]
        }
      }
    ]
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      include: JS_INCLUDES
    })
  ]

@Bastorx
Copy link

Bastorx commented Oct 17, 2017

If you use babel-preset-env :
[ "env", { "targets": { "uglify": true } } ]

@FrancescoMussi
Copy link

I am new entry in the club.
I lost an hour trying all the possible solutions posted above and elsewhere.

The only solution that worked for me was the one posted by @alexey-sh.

But what is going on here?
Isn't this just a workaround in the end?

In my case I encountered the issue after installing a vue component.
But I see that the same issue was reported on dozens of other vue components.

So who is at fault exactly?

Babel, webpack, uglifyJS?

@xuwanwanTT
Copy link

配置要写在rules里面啊啊啊啊。。。
上个月还单独配置loader可以直接编译,真的是。。。
然后我把 exclude: /node_modules/ 删了也可以webpack -p

module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['env']
          }
        }
      }
    ]
  }

@aminnairi
Copy link

aminnairi commented Oct 25, 2017

Just bumped to that issue because I was actually using webpack.optimize.UglifyJsPlugin(). Just did a

$ npm i -D uglifyjs-webpack-plugin

And updated my webpack.config.babel.js like so

import UglifyJS from "uglifyjs-webpack-plugin";
// ...
if (process.env.NODE_ENV === "production")
    config.plugins = [new UglifyJS({/* ... */})];

@naman03malhotra
Copy link

naman03malhotra commented Oct 28, 2017

@aminnairi 's solution worked for me,
Problem is I was running webpack 1 syntax file with webpack 3 which compiled fine except UglifyJs, this problem is elaborated by @jjaeger4
Using https://github.com/webpack-contrib/uglifyjs-webpack-plugin

const UglifyJS = require('uglifyjs-webpack-plugin');
// ....
new UglifyJS({ uglifyOptions: { warnings: false } })

@natterstefan
Copy link

Note: in case someone stumbles upon this issue, after searching for a solution, I add my current working solution notes here.


After reading through this issue and another one in the webpack repository, I got the following two alternative working solutions.

I first installed these packages (Note: babel-preset-es2015 -> babel-preset-env):

>>  package.json

 npm i babel-loader babel-preset-env uglifyjs-webpack-plugin --save-dev

Then I either modified the targets in the .babelrc or the rules in the webpack.config.js:

>> .babelrc

{
  "presets": [
    ["env", {
      "targets": {
        "node": "current",
        "uglify": true // <<< this line
      }
    }],
    "react"
  ],
  // ...
}

or add the options object to the babel-loader.

>> webpack.config.js

// ...
module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {  // << add options with presets env
            presets: ['env']
          }
        }
      }
    ]
}

(thx @xuwanwanTT for the hint)

My webpack config (plugins) looks like this afterwards:

>> webpack.config.js

// ...
plugins: [
  new UglifyJSPlugin({
    test: /\.js($|\?)/i,
    sourceMap: true,
    uglifyOptions: {
        compress: true
    }
  }),
]
// ...

It also works if you use both together. After that webpack -p --config webpack.config.js worked again for me.

@up9cloud
Copy link

up9cloud commented Nov 14, 2017

The new webpack.optimize.UglifyJsPlugin can not parse "let" token
My solution is replacing uglifyjs-webpack-plugin by uglifyes-webpack-plugin

  1. npm i uglifyes-webpack-plugin
  2. edit node_modules/webpack/lib/optimize/UglifyJsPlugin.js (don't do this, thanks @natterstefan )
- const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
+ const UglifyJsPlugin = require("uglifyes-webpack-plugin");
  1. edit build/webpack.prod.conf.js (do this)
+ const UglifyJsPlugin = require("uglifyes-webpack-plugin");
...
  plugins: [
-    new webpack.optimize.UglifyJsPlugin({
+    new UglifyJsPlugin({
...

@natterstefan
Copy link

@up9cloud Don't you think it is kinda dangerous to edit files in the node_modules folder? As other developers need to edit them too and module-upgrades would remove the temporary solution as well/most likely.

@up9cloud
Copy link

@natterstefan umm... you're right. we should avoid to edit node_modules/ content.
edited.

thanks!

@manojkumaran
Copy link

I implemented a solution by combining @aminnairi solution and other ones mentioned above.

npm install uglifyjs-webpack-plugin --save-dev

in webpack config, import this plugin:
const UglifyJs = require('uglifyjs-webpack-plugin');

and in webpack plugins I used this plugin instead of webpack.optimize.UglifyJsPlugin:
new UglifyJs()

@weituotian
Copy link

do not exclude "node_modules"

@devblazer
Copy link

devblazer commented Nov 29, 2017

@up9cloud While that solution does look promising, I think the real problem lies with babel.
Uglify shouldn't have to worry about parsing 'let' keywords, babel should already have transpiled them, unless every current browser in use supports let, in which case I take that statement back, the webpack guys should go ahead and implement your solution lol.

In my case I have one specific file (its a large jsx file) and two very specific lines in it are not being transpiled by babel for some reason?!

if (!this.props.isLoading)
    for (let n = topRowInd; n < Math.min(this.props.dataWrapper.count, topRowInd + rowCount); n++) {
        let clusterMatch = me.props.clusters.reduce((aggr, cluster)=>{
            if (cluster.rowIndStart<=n && cluster.rowIndStart+cluster.rowIndCount>n)
                return cluster;
                    return aggr;
                }, null);
...

Out of this cutout of code, the 'let n' does not transpile to 'var' and the '(aggr, cluster)=>{' does not transpile to 'function (aggr, '. Absolutely every thing else in this file transpiles correctly tho, before it gets to uglify.

@rydergillen-compacSort
Copy link

@up9cloud / @manojkumaran very clean solution. Thank you, this was a major headache

@ghost
Copy link

ghost commented Dec 18, 2017

@manojkumaran For some reason npm install uglifyjs-webpack-plugin --save-dev worked, is the UglifyJs plugin included with webpack.optimize.UglifyJsPlugin() not the same plugin / version?

@rydergillen-compacSort
Copy link

rydergillen-compacSort commented Dec 18, 2017

@megamindbrian You are correct it is not the same version.

https://github.com/webpack-contrib/uglifyjs-webpack-plugin

ℹ️ webpack =< v3.0.0 currently contains v0.4.6 of this plugin under webpack.optimize.UglifyJsPlugin as an alias. For usage of the latest version (v1.0.0), please follow the instructions below. Aliasing v1.0.0 as webpack.optimize.UglifyJsPlugin is scheduled for webpack v4.0.0

@jaganathanb
Copy link

Got it fixed by installing uglifyjs2

@raybooysen
Copy link

Yes, same for me, as well as modifying the config to use the new package instead of the built in one that comes with webpack

@pranayaryal
Copy link

pranayaryal commented Mar 13, 2018

created a .babelrc file. Added this there

{ "presets": [ ["latest", { "es2015": { "modules": false } }] ] }

@himsoftware
Copy link

Hi I am getting the error

0 info it worked if it ends with ok
1 verbose cli [ 'C:\Program Files\nodejs\node.exe',
1 verbose cli 'C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js',
1 verbose cli 'run',
1 verbose cli 'pack:renderer' ]
2 info using npm@5.5.1
3 info using node@v8.9.0
4 verbose run-script [ 'prepack:renderer', 'pack:renderer', 'postpack:renderer' ]
5 info lifecycle field-inspection-app@1.1.0prepack:renderer: field-inspection-app@1.1.0
6 info lifecycle field-inspection-app@1.1.0
pack:renderer: field-inspection-app@1.1.0
7 verbose lifecycle field-inspection-app@1.1.0pack:renderer: unsafe-perm in lifecycle true
8 verbose lifecycle field-inspection-app@1.1.0
pack:renderer: PATH: C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin;C:\GSR\sourcecode\FIELD-ISPECTION-APP\node_modules.bin;C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin;C:\GSR\sourcecode\FIELD-ISPECTION-APP\node_modules.bin;C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin;C:\GSR\sourcecode\FIELD-ISPECTION-APP\node_modules.bin;C:\Program Files\Docker\Docker\Resources\bin;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\iCLS Client;C:\Program Files\Intel\iCLS Client;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0;C:\Program Files (x86)\AMD\ATI.ACE\Core-Static;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Skype\Phone;C:\Program Files\nodejs;C:\Program Files\MongoDB\Server\3.4\bin;C:\Program Files\Git\cmd;C:\Program Files (x86)\Yarn\bin;C:\Users\P10424005\AppData\Local\Microsoft\WindowsApps;C:\Users\P10424005\AppData\Roaming\npm;C:\Program Files\Microsoft VS Code\bin;C:\Users\P10424005\AppData\Local\Programs\Fiddler;C:\Users\P10424005\AppData\Local\Yarn\bin
9 verbose lifecycle field-inspection-app@1.1.0pack:renderer: CWD: C:\GSR\sourcecode\FIELD-ISPECTION-APP
10 silly lifecycle field-inspection-app@1.1.0
pack:renderer: Args: [ '/d /s /c',
10 silly lifecycle 'cross-env NODE_ENV=production webpack -p --progress --colors --config webpack.renderer.config.js' ]
11 silly lifecycle field-inspection-app@1.1.0pack:renderer: Returned: code: 2 signal: null
12 info lifecycle field-inspection-app@1.1.0
pack:renderer: Failed to exec pack:renderer script
13 verbose stack Error: field-inspection-app@1.1.0 pack:renderer: cross-env NODE_ENV=production webpack -p --progress --colors --config webpack.renderer.config.js
13 verbose stack Exit status 2
13 verbose stack at EventEmitter. (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:280:16)
13 verbose stack at emitTwo (events.js:126:13)
13 verbose stack at EventEmitter.emit (events.js:214:7)
13 verbose stack at ChildProcess. (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack at emitTwo (events.js:126:13)
13 verbose stack at ChildProcess.emit (events.js:214:7)
13 verbose stack at maybeClose (internal/child_process.js:925:16)
13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
14 verbose pkgid field-inspection-app@1.1.0
15 verbose cwd C:\GSR\sourcecode\FIELD-ISPECTION-APP
16 verbose Windows_NT 10.0.15063
17 verbose argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "run" "pack:renderer"
18 verbose node v8.9.0
19 verbose npm v5.5.1
20 error code ELIFECYCLE
21 error errno 2
22 error field-inspection-app@1.1.0 pack:renderer: cross-env NODE_ENV=production webpack -p --progress --colors --config webpack.renderer.config.js
22 error Exit status 2
23 error Failed at the field-inspection-app@1.1.0 pack:renderer script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 2, true ]
Please help me its urgent

@harvey56
Copy link

I had this error message :

ERROR in bundle.js from UglifyJs
Unexpected token: name (errors) [bundle.js:82440,5]

I fixed the error by replacing :
plugins = [
new webpack.optimize.UglifyJsPlugin()
]

with :

plugins = [
new UglifyJsPlugin()
]

I'm using version 1.0.1 of the uglifyJS plugin ("uglifyjs-webpack-plugin": "^1.0.1")

@anotherWill
Copy link

//exclude: /(node_modules|bower_components)/,

@kmoec
Copy link

kmoec commented Jun 21, 2018

I was using Webpack 2.7 and was having the same error. Then I decided to upgrade it to version 3. Voila, it resolved my issue.

@parastooveisi
Copy link

Can somebody tell me where to create webpack.config.js? I don't have any in the root directory but there are a lot in other folders in node modules.

I tried all the suggestions but still, the problem exists.

@Neeti24
Copy link

Neeti24 commented May 7, 2021

Thanks, Kmoec
I also update webpack to the latest version and it solved the issue "ERROR in bundle.js from UglifyJs Unexpected token".

johanwestin pushed a commit to whitespace-se/spacecraft that referenced this issue Jun 3, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests