SyntaxError: Unexpected token import Webpack 2 Babel 6 Reactjs

Posted

技术标签:

【中文标题】SyntaxError: Unexpected token import Webpack 2 Babel 6 Reactjs【英文标题】: 【发布时间】:2017-06-08 13:03:27 【问题描述】:

我正在升级 Babel 和 Webpack。我已经查看了这个错误并尝试了我能想到的所有可能性。因此,我不知所措。我很欣赏任何见解。

错误是

SyntaxError: 意外的令牌导入

.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 配置)

    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()
  ]
;

给出的错误是:

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_s-s-r__ = 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');
  );

【问题讨论】:

是来自 .jsx 文件还是 .js 文件的错误 您正在使用 "modules": false 禁用配置中的模块。如果您使用import/export 语法,则需要转换 ES2015 模块。删除该配置。 babeljs.io/docs/plugins/preset-es2015/#options @JoshSpears 错误来自 .js 文件。我之前以 .js 进行了测试(带有 babel-loader 的那个。 @RossAllen 我删除了它,我仍然得到同样的错误,但在不同的位置。 我的意思是,该错误不是来自 Webpack 未能处理文件,而是来自在 Webpack 构建过程中您没有向我们展示实际尝试执行 src/routes.js 的代码。您当前的 Babel 配置告诉 Webpack 在将文件捆绑到输出之前对其进行转译,但是失败的代码并未捆绑在 Webpack 中,而是在 Node 上执行,并且 Node 不知道如何处理 import 【参考方案1】:

感谢大家,我已经解决了这个问题。在我的 .babelrc 文件中,我必须删除 transform-runtime 插件。这解决了它,因为我已经在使用 babel-polyfill。我在某处读到它们可能会相互冲突,因此不应将它们一起使用。

如果其他人碰巧遇到这个问题,我会发布我的 .babelrc 文件以供参考。或者只是举个例子。


  "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"
                ]
              
            ]
          
        ]
      ]
    
  

【讨论】:

以上是关于SyntaxError: Unexpected token import Webpack 2 Babel 6 Reactjs的主要内容,如果未能解决你的问题,请参考以下文章

求教php运行时出错:Parse error: syntax error, unexpected T_STRING, expecting T_FUNCTION 。。。

Import Unexpected identifier + SyntaxError: Unexpected string

js动态加载的a标签的onclick事件参数传递,一直报Uncaught SyntaxError: Invalid or unexpected token

解析错误:语法错误,意外的“未设置”(T_UNSET)

SyntaxError: unexpected EOF while parsing

获取 MongoDB 错误 - SyntaxError: Unexpected token?