Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyntaxError: Unexpected token import [duplicate]

I have this code:

"use strict";

import browserSync from "browser-sync";
import httpProxy from "http-proxy";

let proxy = httpProxy.createProxyServer({});

and I have installed babel-core and babel-cli globally via npm. The point is when I try to compile with this on my terminal:

babel proxy.js --out-file proxified.js

The output file gets copied instead of compiled (I mean, it's the same as the source file).

What am I missing here?

like image 916
Raul Vallespin Avatar asked Oct 30 '15 16:10

Raul Vallespin


4 Answers

Babel is a transformation framework. Pre-6.x, it enabled certain transformations by default, but with the increased usage of Node versions which natively support many ES6 features, it has become much more important that things be configurable. By default, Babel 6.x does not perform any transformations. You need to tell it what transformations to run:

npm install babel-preset-env

and run

babel --presets env proxy.js --out-file proxified.js

or create a .babelrc file containing

{
    "presets": [
        "env"
    ]
}

and run it just like you were before.

env in this case is a preset which basically says to compile all standard ES* behavior to ES5. If you are using Node versions that support some ES6, you may want to consider doing

{
    "presets": [
        ["env", { "targets": { "node": "true" } }],
    ]
}

to tell the preset to only process things that are not supported by your Node version. You can also include browser versions in your targets if you need browser support.

like image 105
loganfsmyth Avatar answered Nov 11 '22 15:11

loganfsmyth


First ensure you have the following node modules:

npm i -D webpack babel-core babel-preset-es2015 babel-preset-stage-2 babel-loader

Next, add this to your Webpack config file (webpack.config.js) :

// webpack.config.js
...
module  :  {
  loaders  :  [
    {
      test    :  /\.js$/,
      loader  :  'babel',
      exclude :  /node_modules/,
      options :  {
        presets  :  [ 'es2015', 'stage-2' ] // stage-2 if required
      } 
    } 
  ]
}
...

References:

  • https://gist.github.com/Couto/6c6164c24ae031bff935
  • https://github.com/babel/babel-loader/issues/214

Good Luck!

like image 30
Aakash Avatar answered Nov 11 '22 16:11

Aakash


Most of these answers are obsolete. @babel/preset-env and "@babel/preset-react are what you need (as of July 2019).

like image 5
mmla Avatar answered Nov 11 '22 16:11

mmla


I had the same problem with a different cause:

The code I was trying to load was not under the package directory, and Babel does not default to transpiling outside the package directory.

I solved it by moving the imported code, but perhaps I could have also used some inclusion statement in the Babel configuration.

like image 3
w00t Avatar answered Nov 11 '22 16:11

w00t