简体   繁体   English

SyntaxError:意外的令牌导入Webpack 2 Babel 6 Reactjs

[英]SyntaxError: Unexpected token import Webpack 2 Babel 6 Reactjs

I am in the process of upgrading Babel and Webpack. 我正在升级Babel和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 SyntaxError:意外的令牌导入

.babelrc .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) dev.config.js(devpack的webpack配置)

    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 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 斌/ 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');
  });

Thanks to everybody I have figured out the issue. 感谢大家,我已经找到了问题。 In my .babelrc file, I had to remove the transform-runtime plugin. 在我的.babelrc文件中,我不得不删除transform-runtime插件。 This fixed it because I was already using babel-polyfill. 这固定了因为我已经使用了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. 我会发布我的.babelrc文件以供参考,如果有其他人碰巧碰到这个。 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"
                ]
              }
            ]
          }
        ]
      ]
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM