3

I am in the process of upgrading Babel and Webpack. I have looked this error up and have tried all possibilities I could think of. Thus, I am at a loss. I appreciate any insight.

The Error is

SyntaxError: Unexpected token import

.babelrc

{
  "presets": [
    "es2015",
    "react",
    "stage-0"
  ],
  "plugins": [
    "add-module-exports",
    "transform-decorators-legacy",
    "transform-runtime",
    "transform-react-display-name"
  ],
  "env": {
    "development": {
      "plugins": [
        "typecheck",
        [
          "react-transform",
          {
            "transforms": [
              {
                "transform": "react-transform-catch-errors",
                "imports": [
                  "react",
                  "redbox-react"
                ]
              }
            ]
          }
        ]
      ]
    }
  }
}

dev.config.js (webpack config for dev)

    require('babel-polyfill');

    // Webpack config for development
    var fs = require('fs');
    var path = require('path');
    var webpack = require('webpack');
    var assetsPath = path.resolve(__dirname, '../static/dist');
    var host = (process.env.HOST || 'localhost');
    var port = parseInt(process.env.PORT) + 1 || 3001;
    var themePath = path.join(__dirname, '../src/theme');

    // https://github.com/halt-hammerzeit/webpack-isomorphic-tools
    var WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');
    var webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(require('./webpack-isomorphic-tools'));

    var babelrc = fs.readFileSync('./.babelrc');
    var babelrcObject = {};

    try {
      babelrcObject = JSON.parse(babelrc);
    } catch (err) {
      console.error('==>     ERROR: Error parsing your .babelrc.');
      console.error(err);
    }

    var babelrcObjectDevelopment = babelrcObject.env && babelrcObject.env.development || {};

    // merge global and dev-only plugins
    var combinedPlugins = babelrcObject.plugins || [];
    combinedPlugins = combinedPlugins.concat(babelrcObjectDevelopment.plugins);

    var babelLoaderQuery = Object.assign({}, babelrcObjectDevelopment, babelrcObject, {plugins: combinedPlugins});
    delete babelLoaderQuery.env;

    // Since we use .babelrc for client and server, and we don't want HMR enabled on the server, we have to add
    // the babel plugin react-transform-hmr manually here.

    // make sure react-transform is enabled
    babelLoaderQuery.plugins = babelLoaderQuery.plugins || [];
    var reactTransform = null;
    for (var i = 0; i < babelLoaderQuery.plugins.length; ++i) {
      var plugin = babelLoaderQuery.plugins[i];
      if (Array.isArray(plugin) && plugin[0] === 'react-transform') {
        reactTransform = plugin;
      }
    }

    if (!reactTransform) {
      reactTransform = ['react-transform', {transforms: []}];
      babelLoaderQuery.plugins.push(reactTransform);
    }

    if (!reactTransform[1] || !reactTransform[1].transforms) {
      reactTransform[1] = Object.assign({}, reactTransform[1], {transforms: []});
    }

    // make sure react-transform-hmr is enabled
    reactTransform[1].transforms.push({
      transform: 'react-transform-hmr',
      imports: ['react'],
      locals: ['module']
    });

    module.exports = {
      devtool: 'inline-source-map',
      context: path.resolve(__dirname, '..'),
      entry: {
        'main': [
          'webpack-hot-middleware/client?path=http://' + host + ':' + port + '/__webpack_hmr',
          `bootstrap-loader?configFilePath=${themePath}/bs3.yml`,
          'font-awesome-webpack!./src/theme/font-awesome.config.js',
          './src/client.js'
        ]
      },
      output: {
        path: assetsPath,
        filename: '[name]-[hash].js',
        chunkFilename: '[name]-[chunkhash].js',
        publicPath: 'http://' + host + ':' + port + '/dist/'
      },
      module: {
        rules: [
          {
            test: /\.jsx$/,
            exclude: /node_modules/,
            use: [
              {
                loader:'babel-loader?' + JSON.stringify(babelLoaderQuery)
              },
              'eslint-loader']
          },
          {
            test: /\.css$/,
            use: [
              'style-loader',
              {
                loader: 'css-loader',
                options: { importLoaders: 1 }
              },
              'postcss-loader'
            ]
          },
          {
            test: /\.less$/,
            use: [
              'style-loader',
              {
                loader: 'css-loader',
                options: { modules: true, importLoaders: 2, sourceMap: true, localIdentName: 'local]___[hash:base64:5]' }
              },
              'postcss-loader',
              {
                loader: 'less-loader',
                options: { outputStyle: "expanded", sourceMap: 'true' }
              }]
          },
          {
            test: /\.scss$/,
            use: [
              { loader: 'style-loader' }, {
                loader: 'css-loader?sourceMap',
                options: { sourceMap: true, importLoaders: 2 }
              },
              'postcss-loader',
              {
                loader: 'sass-loader',
                options: { outputStyle: "expanded", sourceMap: 'true' }
              }]
          },
          {
            test: /.(woff(2)?)(\?[a-z0-9=\.]+)?$/,
            use: [
              {
                loader: 'url-loader',
                options: { limit: 10000, mimetype: 'application/font-woff' }
              }
            ]
          },
          { test: /.(eot)(\?[a-z0-9=\.]+)?$/, loader: 'file-loader' },
          {
            test: /.(ttf)(\?[a-z0-9=\.]+)?$/,
            use: [
              {
            loader: 'url-loader',
            options: { limit: 10000, mimetype: 'application/octet-stream' }
          }
        ]
      },
      {
        test: /.(svg)(\?[a-z0-9=\.]+)?$/,
        use: [
          {
            loader: 'url-loader',
            options: { limit: 10000, mimetype: 'image/svg+xml' }
          }
        ]
      },
      // {test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream'},
      // {test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file'},
      // {test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml'},
      // {test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/font-woff'},
      { test: webpackIsomorphicToolsPlugin.regular_expression('images'), loader: 'url-loader?limit=10240' }
    ]
  },
  resolve: {
    modules: [
      'src',
      'node_modules'
    ],
    extensions: ['.json', '.js', 'jsx']
  },
  plugins: [
    // hot reload
    new webpack.HotModuleReplacementPlugin(),
    new webpack.IgnorePlugin(/webpack-stats\.json$/),
    new webpack.DefinePlugin({
      __CLIENT__: true,
      __SERVER__: false,
      __DEVELOPMENT__: true,
      __DEVTOOLS__: true  // <-------- DISABLE redux-devtools HERE
    }),
    webpackIsomorphicToolsPlugin.development()
  ]
};

error given was:

SyntaxError: Unexpected token import
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:404:25)
at loader (/Users/stevenhawley/Dev/com.fdc.app.ui/node_modules/babel-register/lib/node.js:144:5)
at Object.require.extensions.(anonymous function) [as .js] (/Users/stevenhawley/Dev/com.fdc.app.ui/node_modules/babel-register/lib/node.js:154:7)
at Module.load (module.js:356:32)
at Module._load (module.js:313:12)
at Function.module._load (/Users/stevenhawley/Dev/com.fdc.app.ui/node_modules/piping/lib/launcher.js:32:16)
at Module.require (module.js:366:17)
at require (module.js:385:17)
at Object.<anonymous> (/Users/stevenhawley/Dev/com.fdc.app.ui/src/routes.js:4:1)

routes.js

import React from 'react';
import {IndexRoute, Route} from 'react-router';
import { isLoaded as isAuthLoaded, isLoading as isAuthLoading, load as loadAuth, hasRolesFetchData } from 'redux/modules/auth';
import {
  AddressValidation,
  App,
  Carriers,
  CarrierMethods,
  Home,
  Inventory,
  Login,
  Merchants,
  Merchant,
  Orders,
  Order,
  Printers,
  Products,
  Users,
  User,
  ReportSubscriptions,
  ReturnsTool,
  Skus,
  NotFound,
  NotForYou,
  WarehouseHolidays,
  Warehouses,
  WeighStation,
  ShipMethods,
  ACL
} from 'containers';

export default (store) => {
  const requireLogin = (nextState, replace, cb) => {
    function checkAuth() {
      const { auth: { account }} = store.getState();
      if (!account) {
        // oops, not logged in, so can't be here!
        const query = nextState.location.query;
        query.nextPath = nextState.location.pathname;
        // {nextPath: nextState.location.pathname, nextQuery: nextState.location.search}
        replace({pathname: `/login`, query: query});
      } else if (!hasRolesFetchData(store.getState(), ['fdc', 'admin', 'developer'])) {
        replace({pathname: '/sorry'});
      }
      cb();
    }
    const state = store.getState();
    if (!isAuthLoaded(state) && !isAuthLoading(state)) {
      console.log('==== requireLogin, auth not loaded ===');
      store.dispatch(loadAuth()).then((resolved) => {
        // console.log('[Router] loadAuth resolved!');
        // console.log(resolved);
        checkAuth();
      }, (rejected) => {
        // console.log('[Router] loadAuth rejected!');
        // console.log(rejected);
        checkAuth();
      });
    } else {
      checkAuth();
    }
  };

  /**
   * Please keep routes in alphabetical order
   */
  return (
    <Route path="/" component={App}>
      { /* Home (main) route */ }
      <IndexRoute component={Home}/>

      { /* Routes requiring login */ }
      <Route onEnter={requireLogin}>
        <Route path="addressValidation" component={AddressValidation}/>
        <Route path="carriers" component={Carriers}/>
        <Route path="carrierMethods" component={CarrierMethods}/>
        <Route path="inventory" component={Inventory}/>
        <Route path="merchants/shippingMethods" component={ShipMethods}/>
        <Route path="merchants/:id" component={Merchant}/>
        <Route path="merchants" component={Merchants}/>
        <Route path="orders" component={Orders}/>
        <Route path="orders/:id" component={Order}/>
        <Route path="printers" component={Printers}/>
        <Route path="products" component={Products}/>
        <Route path="reportSubscriptions" component={ReportSubscriptions}/>
        <Route path="returnsTool" component={ReturnsTool}/>
        <Route path="skus" component={Skus}/>
        <Route path="users" component={Users}/>
        <Route path="users/:id" component={User}/>
        <Route path="warehouseHolidays" component={WarehouseHolidays}/>
        <Route path="warehouses" component={Warehouses}/>
        <Route path="weighStation" component={WeighStation}/>
        <Route path="acl" components={ACL} />
      </Route>

      { /* Routes */ }
      <Route path="login" component={Login}/>
      <Route path="sorry" component={NotForYou}/>

      { /* Catch all route */ }
      <Route path="*" component={NotFound} status={404}/>
    </Route>
  );
};

bin/server.js

#!/usr/bin/env node
require('../server.babel'); // babel registration (runtime transpilation for node)
var path = require('path');
var rootDir = path.resolve(__dirname, '..');
/**
 * Define isomorphic constants.
 */
global.__CLIENT__ = false;
global.__SERVER__ = true;
global.__DISABLE_SSR__ = false;  // <----- DISABLES SERVER SIDE RENDERING FOR ERROR DEBUGGING
global.__DEVELOPMENT__ = process.env.NODE_ENV !== 'production';

if (__DEVELOPMENT__) {
  if (!require('piping')({
      hook: true,
      ignore: /(\/\.|~$|\.json|\.scss$)/i
    })) {
    return;
  }
}

// https://github.com/halt-hammerzeit/webpack-isomorphic-tools
var WebpackIsomorphicTools = require('webpack-isomorphic-tools');
global.webpackIsomorphicTools = new WebpackIsomorphicTools(require('../webpack/webpack-isomorphic-tools'))
  .server(rootDir, function() {
    require('../src/server');
  });
TwistedSt
  • 632
  • 1
  • 6
  • 14
  • Is the error from a .jsx file or .js file – Josh Jan 23 '17 at 21:44
  • 1
    You are disabling modules in your config with `{"modules": false}`. If you are using the `import`/`export` syntax, you need to transform ES2015 modules. Remove that config. https://babeljs.io/docs/plugins/preset-es2015/#options – Ross Allen Jan 23 '17 at 21:46
  • @JoshSpears The error is from a .js file. I had the test as .js previously (the one with the babel-loader. – TwistedSt Jan 23 '17 at 21:52
  • @RossAllen I removed it and I still get the same error, but at a different location. – TwistedSt Jan 23 '17 at 21:54
  • @TwistedSt I only see you testing .jsx files. Look at my simple webpack file here: https://github.com/JoshSpears3/React-Portfolio/blob/master/webpack.config.js. You can see I test both .jsx files and .js files. – Josh Jan 23 '17 at 21:55
  • Please post the full error message. – loganfsmyth Jan 23 '17 at 21:56
  • @JoshSpears I see what you mean. I made the changes to test for both and I am still getting the same error. – TwistedSt Jan 23 '17 at 21:58
  • Your error is coming from `src/routes.js` which seems unrelated to Webpack. It sounds like you're running the server side of your application? – loganfsmyth Jan 23 '17 at 22:01
  • @loganfsmyth I posted and thank you for editing it for me. :) – TwistedSt Jan 23 '17 at 22:01
  • @loganfsmyth That is correct. It is having issues importing modules from another folder. I properly export the modules. This worked before in previous versions of Webpack and Babel. – TwistedSt Jan 23 '17 at 22:02
  • 1
    My point is, that error is not from Webpack failing to process the files, it is from code that you have not shown us actually attempting to execute `src/routes.js` during during Webpack's build process. Your current Babel config tells Webpack to transpile files before bundling them into the output, but the code that is failing isn't getting bundled in Webpack, it is executing on Node, and Node doesn't know how to handle `import`. – loganfsmyth Jan 23 '17 at 22:11
  • I do see what you mean. I posted the server.js file that breaks. Sorry about the delay, I was attempting to look into that more. – TwistedSt Jan 23 '17 at 22:34

1 Answers1

2

Thanks to everybody I have figured out the issue. In my .babelrc file, I had to remove the transform-runtime plugin. This fixed it because I was already using babel-polyfill. I read somewhere that they can conflict with each other, so they shouldn't be used together.

I'll post my .babelrc file for reference if anyone else happens to run into this. Or simply to use an example.

{
  "presets": [
    "es2015",
    "react",
    "stage-0"
  ],
  "plugins": [
    "add-module-exports",
    "transform-decorators-legacy",
    "transform-react-display-name"
  ],
  "env": {
    "development": {
      "plugins": [
        "typecheck",
        [
          "react-transform",
          {
            "transforms": [
              {
                "transform": "react-transform-catch-errors",
                "imports": [
                  "react",
                  "redbox-react"
                ]
              }
            ]
          }
        ]
      ]
    }
  }
}
TwistedSt
  • 632
  • 1
  • 6
  • 14