joeeames / WebpackFundamentalsCourse

272 stars 122 forks source link

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

Closed MBing closed 8 years ago

MBing commented 8 years ago

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!

willjones2k commented 7 years ago

Since uglify doesn't fully support es6 in the build, you can specify it in your .babelrc file.
(in addition to babel-core and babel-loader add...) npm install babel-preset-env --save-dev

In your .babelrc file

{ "presets": [ ["env", { "targets": { "uglify": false } }] ] }

DanDvoracek commented 7 years ago

Thanks for this thread! It was nearly an hour I've been trying things out. @danielabar 's solution worked for me 💯

aciurea commented 7 years ago

on my side the problem was that it didn't transpile the code so when it tried to minify the error occured. In order to fix it I replaced: test: /.es6$/, with test: /.js$/,

ErikFontanel commented 7 years ago

solution by @willjones2k worked for me with Webpack 3.0.0

kaleemullah360 commented 7 years ago

Experienced same problem, I tried adding

{
  "presets": ["es2015"]
}

in .babelrc and installed npm install babel --save-dev npm install --save-dev babel-preset-es2015

there is no webpack config js file in my project dir. any suggestions ?

dotspencer commented 7 years ago

I was getting the same error with a React.js app. Solved the problem by adding babel-preset-es2015 to dev dependencies and to the babel presets in my package.json.

npm i -D babel-preset-es2015
"babel": {
    "presets": [
      "react",
      "babel-preset-es2015"
    ]
  }
janthonyeconomist commented 7 years ago

I don't know if this is helpful to anyone else, but what I was seeing was, I use .babelrc just to parse my gulpfile.babel.js, and then in gulp I was passing all my configurations directly to my webpack driver to build the JS for the whole site. The problem was that (even though I was explicitly passing my config) it was also picking up the .babelrc file and overriding the manual configs. Not sure if this is a sane default; however, you can tell the babel-loader plugin to ignore your .babelrc file.

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            "only": "src/js/**",
            "presets": [
              "flow",
              "react",
              ["env", {
                "targets": {
                  "browsers": "last 2 versions"
                },
                "useBuiltIns": true
              }]
            ],
            "plugins": ["transform-class-properties", "syntax-dynamic-import"],
            "babelrc": false,
          }
        },
      }
    ]
  },
escarrgot commented 7 years ago

For those using Webpack Version 3.0.0 this helped me:

  1. Remove babel-loader from loaders and instead place it under rules
//...
    module: {
      rules: [
          {
              test: /\.js$/,
              enforce: 'pre',
              exclude: /node_modules/,
              use: [
                {
                    loader: 'jshint-loader'
                }
            ]
        },
        {
            test: [/\.es6$/, /\.js$/],
            exclude: /node_modules/,
            use: {
              loader: 'babel-loader',
              options: {
                presets: ['env']
                }
            }
        }
    ],
      loaders: [
      ]
    },
//...
  1. Modify test to include .js files (already included in above snippet).
  2. In the console run npm install babel-preset-env --save-dev
  3. Then try running webpack -p in the console again.

Hope this solves the problem for others.

trusktr commented 7 years ago

These seems too common of a problem, and merits being officially addressed with a solution.

As mentioned there, an easy alternative is to use babili-webpack-plugin instead of Webpack's builtin UglifyJSPlugin.

vasilGerginski commented 7 years ago

Check if "login" is declared using "let" and try changing it to var. ERROR in bundle.js from UglifyJs Unexpected token: name (login) [./login.es6:2,4]

alexey-sh commented 7 years ago

Too many comments above. I've just removed

new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        }),

and all works fine. no plugin no problem

ken90242 commented 7 years ago

@ahmad2smile thank you!!!!!!!

tkgkn commented 7 years ago

use babel-loader can solve this problem~ module: { rules: [{ test: /\.js$/, include: [path.resolve(__dirname,'src/')], use: [{ loader: 'babel-loader', options: { presets: ['es2015'] } }] }] }

jjaeger4 commented 7 years ago

Resolution (for me): Same issues, resolved. This may only pertain to my own setup. I was following the course videos and knew that I could come here if issues came about but I made the mistake of copying @joeeames package.json file 100% and doing an npm install which resulted in a webpack version of 1.12.9 where-as webpack (as of today) is on a current release of 3.6.0.

I was including everyone's recommendations (from here) and getting no-where. Turned out to be that I had a big mess of hybrid code all trying to work on an outdated version of webpack.

Check your Webpack version: npm list webpack

If you are out of date and trying to use "rules" instead of "loaders" and "use" instead of "loader": npm uninstall webpack --save-dev npm install webpack --save-dev

Bastorx commented 7 years ago

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

FrancescoMussi commented 7 years ago

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 commented 7 years ago

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

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

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 commented 6 years ago

@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 commented 6 years ago

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 commented 6 years ago

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");
  3. edit build/webpack.prod.conf.js (do this)

    + const UglifyJsPlugin = require("uglifyes-webpack-plugin");
    ...
    plugins: [
    -    new webpack.optimize.UglifyJsPlugin({
    +    new UglifyJsPlugin({
    ...
natterstefan commented 6 years ago

@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 commented 6 years ago

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

thanks!

manojkumaran commented 6 years ago

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 commented 6 years ago

do not exclude "node_modules"

devblazer commented 6 years ago

@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 commented 6 years ago

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

ghost commented 6 years ago

@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 commented 6 years ago

@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 commented 6 years ago

Got it fixed by installing uglifyjs2

raybooysen commented 6 years ago

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 commented 6 years ago

created a .babelrc file. Added this there

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

himsoftware commented 6 years ago

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.0~prepack: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.0~pack: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.0~pack: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.0~pack: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 commented 6 years ago

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 commented 6 years ago

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

kmoec commented 6 years ago

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 commented 5 years ago

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 commented 3 years ago

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