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!

gfunk1230 commented 8 years ago

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

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

@joeeames thanks so much and have a Happy Thanksgiving.

joeeames commented 8 years ago

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

jurrinus commented 8 years ago

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

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

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

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

danielabar commented 8 years ago

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

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

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

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

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

That would be excellent @hopcycle!

MartinMuzatko commented 8 years ago

Same issue here.

james-world commented 8 years ago

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

Thanks @danielabar.

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

loaders: [  {
    test: /\.js$/,
        loader: 'babel',
        query: {
          presets: ['es2015']
        }
    }
]
tarun2502 commented 8 years ago

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

mjt60 commented 8 years ago

+1 for @danielabar's solution.

brunobritodev commented 8 years ago

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

I have the same error in webpack 2 with typescript 2

LanderBeeuwsaert commented 8 years ago

Same here: webpack 2, typescript 2

kesarion commented 8 years ago

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

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:

OR,

Ch4s3 commented 7 years ago

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

+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
    })
  ]
coreylight commented 7 years ago

In my case I had accidentally left the .js extension off one of my files, so babel wasn't running on it first before uglify.

lwkz commented 7 years ago

Using webpack@2.2.0-rc.1 + babel 6.21 and seeing the same error.

Installed "babel-core": "^6.21.0", "babel-loader": "^6.2.10", "babel-preset-es2015": "^6.18.0".

tried

module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: 'babel-loade',
        exclude: /(node_modules|bower_components)/,
        query: {
          presets: ['es2015']
        }
      },
    ],
  },

with no luck, however it works when I use

module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: 'babel-loader?presets[]=es2015',
        exclude: /(node_modules|bower_components)/,
      },
    ],
  },

Webpack 2 doesn't read query settings anymore?

sokra commented 7 years ago

The syntax is invalid (we should have better validation here). That's what's possible:

rules: [
  {
    loader: "babel-loader",
    options: {}
  },
  {
    use: {
      loader: "babel-loader",
      options: {}
    }
  },
  {
    use: [
      {
        loader: "babel-loader",
        options: {}
      }
    ]
  }
]

options could be exchanged with query

lwkz commented 7 years ago

tried both

        options: {
          query: {
            presets: ['es2015'],
          },
        },

and

        options: {
            presets: ['es2015'],
        },

and still getting the same error, am I missing something?

Thanks,

sokra commented 7 years ago

loader and options must be a pair. use it the container for the results. loader is one result.

Here is a syntax that will definitely work, because it's in the test suite:

https://github.com/webpack/webpack/blob/master/test/configCases/loaders/issue-3320/webpack.config.js#L17-L27

lwkz commented 7 years ago

Thanks. I didn't realise options has to be inside use. Will watch #3556

rules: [
      {
        test: /\.(js|jsx)$/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: ['es2015'],
            },
          },
        ],
      },
    ],
  },

works fine.

mdopieralski commented 7 years ago

+1

:(

bebensiganteng commented 7 years ago

Webpack 2 + typescript.

Tried @kesarion solution and the ts-loader's example, nothing works.

Below is the error;

$ webpack -p

ERROR in scripts/app.js from UglifyJs
SyntaxError: Unexpected token: name (App) [scripts/app.js:10571,6]

Typescript code;

import style from '../css/top.scss'
import $ from 'jquery'

class App {

  constructor() {
     //TEST
  }
}

$(document).ready(()=> {

  let app = new App();

});

Webpack modules setting;

        rules: [
            {
                test: /\.ts$/,
                loader: 'ts-loader',
                exclude: /node_modules/
            }
        ],
smallsaucepan commented 7 years ago

Not a Typescript user, however saw this reference which may be of use to some: https://github.com/AngularClass/angular2-webpack-starter/issues/853#issuecomment-278542609

Got me headed in the right direction to fix my JSX issue.

hamidraza commented 7 years ago

+1

janthonyeconomist commented 7 years ago

Hi All,

I think I'm experiencing the same Uglify incompatibility problem. I'm using webpack and webpack-stream to integrate with my gulp build system. I'm using the babel-loader; however, the system seems to fail at compression. Below is my code.

gulp.task('scripts', () => {
  const WEBPACK_CONFIG = {
    devtool: 'source-map',
    module: {
      rules: [{
        test: /.jsx?$/,
        include: 'src/js/includes',
        exclude: /node_modules/,
        use: [{
          loader: 'babel-loader',
          options: {
            presets: ['es2015', 'react'],
            plugins: ['transform-runtime'],
            cacheDirectory: '.tmp/js',
          }
        }],
      }],
    },
    plugins: [
      new webpack.DefinePlugin({
        'process.env': {
          // This has effect on the react lib size
          'NODE_ENV': JSON.stringify('production')
        }
      }),
        new webpack.optimize.UglifyJsPlugin()
    ]
  };
  return gulp.src([
    'src/js/main.js',
    'src/js/desktop-only.js',
  ])
    .pipe(named())
    .pipe(webpackStream(WEBPACK_CONFIG))
    .pipe(gulp.dest('build/js'));
});

Is there another way to implement compression with Webpack2? Should I just stream the output of webpack through gulp-uglify? Am I missing the mark. Is this a red herring?

BTW, below is my error:

janthony-mac:src judahanthony$ gulp scripts
[16:08:52] Requiring external module babel-register
[16:08:52] Using gulpfile ~/workspace/src/gulpfile.babel.js
[16:08:52] Starting 'scripts'...

stream.js:74
      throw er; // Unhandled stream error in pipe.
      ^
Error: desktop-only.js from UglifyJs
Unexpected token: punc ({) [desktop-only.js:54,8]main.js from UglifyJs
Unexpected token: name ($) [main.js:56,8]
joaomilho commented 7 years ago

+1

MatthewJamesBoyle commented 7 years ago

Experiencing the same issue, +1 from me too.

fbnz156 commented 7 years ago

Same issue. How is this still going 2 years later?

janthonyeconomist commented 7 years ago

I think my problem, was the Babel loader was not translating my ES6 code, so the Uglify plugin was choking on the unfamiliar syntax.

Judah Anthony Technology Director Which MBA? p 212.554.0611 e judahanthony@economist.com im janthonyeconomist (Skype)

On Thu, Mar 9, 2017 at 9:08 PM, avatarscape notifications@github.com wrote:

Same issue. How is this still going 2 years later?

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/joeeames/WebpackFundamentalsCourse/issues/3#issuecomment-285552145, or mute the thread https://github.com/notifications/unsubscribe-auth/ABEMnxYZb1UOnsc1NSbZSyppjYUb5BV-ks5rkLCvgaJpZM4GgiQR .

-- This e-mail may contain confidential material. If you are not an intended recipient, please notify the sender and delete all copies. It may also contain personal views which are not the views of The Economist Group. We may monitor e-mail to and from our network.

Sent by a member of The Economist Group. The Group's parent company is The Economist Newspaper Limited, registered in England with company number 236383 and registered office at 25 St James's Street, London, SW1A 1HG. For Group company registration details go to http://legal.economistgroup.com http://legal.economistgroup.com

fbnz156 commented 7 years ago

Changing to es5 in tsconfig fixed this.

On 10 Mar 2017 14:59, "Judah Anthony" notifications@github.com wrote:

I think my problem, was the Babel loader was not translating my ES6 code, so the Uglify plugin was choking on the unfamiliar syntax.

Judah Anthony Technology Director Which MBA? p 212.554.0611 e judahanthony@economist.com im janthonyeconomist (Skype)

On Thu, Mar 9, 2017 at 9:08 PM, avatarscape notifications@github.com wrote:

Same issue. How is this still going 2 years later?

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/joeeames/WebpackFundamentalsCourse/ issues/3#issuecomment-285552145, or mute the thread https://github.com/notifications/unsubscribe-auth/ ABEMnxYZb1UOnsc1NSbZSyppjYUb5BV-ks5rkLCvgaJpZM4GgiQR .

-- This e-mail may contain confidential material. If you are not an intended recipient, please notify the sender and delete all copies. It may also contain personal views which are not the views of The Economist Group. We may monitor e-mail to and from our network.

Sent by a member of The Economist Group. The Group's parent company is The Economist Newspaper Limited, registered in England with company number 236383 and registered office at 25 St James's Street, London, SW1A 1HG. For Group company registration details go to http://legal.economistgroup.com http://legal.economistgroup.com

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/joeeames/WebpackFundamentalsCourse/issues/3#issuecomment-285690045, or mute the thread https://github.com/notifications/unsubscribe-auth/ABIw2oQktgJrhV5a8j4K1HBaLnb6EOQvks5rkWVFgaJpZM4GgiQR .

felek000 commented 7 years ago

Hello i have similar issue i try everything i install all modules using yarn is that might be a problem ?

from UglifyJs Unexpected token: name

webpack.config.js var webpack = require('webpack'); const ExtractTextPlugin = require("extract-text-webpack-plugin"); var pathDist = './dist/'; var pathSrc = './src/';

const extractSass = new ExtractTextPlugin({ filename: pathDist+"main.css", disable: process.env.NODE_ENV === "development" });

module.exports = { entry: pathSrc+'js/app.js', devtool: "source-map", // any "source-map"-like devtool is possible output: { filename: pathDist+'bundle.js' }, module: { loaders: [ {test:/.html$/}, { test: /.js$/, exclude: /node_modules/, loader: 'babel-loader', query: { presets: ['es2015'] } } ], rules: [{ test: /.scss$/, loader: extractSass.extract({ loader: [{ loader: "css-loader", options: { sourceMap: true } }, 'postcss-loader', { loader: "sass-loader", options: { sourceMap: true } }], // use style-loader in development fallbackLoader: "style-loader" }) }] }, plugins: [ new webpack.ProvidePlugin({ jQuery: 'jquery', $: 'jquery', jquery: 'jquery' }), extractSass, new webpack.optimize.UglifyJsPlugin({ minimize: true, compress: false }) ] }

sample dumy files test.js

class Test { constructor(){

}

run(){
    $(document).ready(function(){
        $('#myModal').modal('show');
        console.log('zzzfdssdfzzzzzzz');
    });
}

} export default Test;

app.js import 'jquery'; import 'bootstrap-sass/assets/javascripts/bootstrap';

import Test from './test'; var test = new Test(); test.run();

//css file import '../scss/main.scss';

$(document).ready(()=>{

var a = 1;
// $('#myModal').modal('show');

console.log(`tesdfdsfsdssst ${a}`);

});

What im doing wrong ?

wnadurski commented 7 years ago

I had the same issue and found out that one of my dependencies uses es6's "let" keyword. As "node_modules" is excluded from transpilation in my webpack config, uglifyjs could not process it properly.

styfle commented 7 years ago

@wnadurski Yes this was the fix surprisingly! I was able to do webpack -d no problem but webpack -p failed with UglifyJS error. It turns out changing my tsconfig.json from ES6 to ES5 made it work!

See https://github.com/mishoo/UglifyJS2/issues/448

triunity commented 7 years ago

e.g. file which name is ".babelrc", { "presets": ["es2015"], "compact" : false }

ghost commented 7 years ago

https://www.npmjs.com/package/uglify-js-harmony

ahmad2smile commented 7 years ago

TL;DR

add .babelrc and babel-preset-es2015

yerol commented 7 years ago

UglifyJs does not support block scoping. If the code is somehow not transpiled properly, then UglifyJs blows up. es2015 preset should sort this problem out but particularly, if you only use a few transforms rather than a complete preset, you'll need "transform-es2015-block-scoping".

npm install --save-dev babel-plugin-transform-es2015-block-scoping

{
  "plugins": ["transform-es2015-block-scoping"]
}

More details on installing it below.

http://babeljs.io/docs/plugins/transform-es2015-block-scoping/

GaryChangCN commented 7 years ago

for webpack2.0 use

{
            test: /\.(tsx|ts)$/,
            use: ["babel-loader","ts-loader"],
            exclude: "/node_modules/"
        }

instead of

        {
            test: /\.(tsx|ts)$/,
            loader: "ts-loader",
            exclude: "/node_modules/"
        }

and tsconfig.json

{
  "compilerOptions": {
    "target": "es2015",
    "jsx": "react"
  }
}

and .babelrc

{
  "presets": ["es2015", "react", "stage-0"]
}

because ts has compiler tsx to es6 and uglifyJS can't compress ES6. To slove this problem ,use babel convert it to es5 which is build convert by ts.