带有babel-loader的Webpack无法识别导入关键字

时间:2015-08-04 02:06:44

标签: javascript ecmascript-6 webpack babeljs transpiler

我有webpack.config.js

module.exports = {
  entry: './src/admin/client/index.jsx',
  output: {
    filename: './src/admin/client/static/js/app.js'
  },
  loaders: [
    {
      test: /\.jsx?$/,
      loader: 'babel',
      exclude: /node_modules/,
      query: {
        optional: ['runtime']
      }
    }
  ],
  resolve: {
    extensions: ['', '.js', '.jsx']
  }
};

...但我仍然收到此错误:

$ webpack -v
Hash: 2a9a40224beb025cb433
Version: webpack 1.10.5
Time: 44ms
   [0] ./src/admin/client/index.jsx 0 bytes [built] [failed]

ERROR in ./src/admin/client/index.jsx
Module parse failed: /project/src/admin/client/index.jsx Line 1: Unexpected reserved word
You may need an appropriate loader to handle this file type.
| import React from 'react';
| import AdminInterface from './components/AdminInterface';

我有:

  • 全局和本地安装webpack
  • 已安装babel-loaderbabel-corebabel-runtime
  • 全局安装babel-loader,以防万一

为什么webpack似乎无视babel-loader?或者babel-loader不适用于模块吗?

更新

看起来babel处理输入文件就好了。我跑的时候:

./node_modules/babel/bin/babel.js ./src/admin/client/index.jsx

...按预期输出ES5。因此,在我看来webpack不能正确加载babel-loader

3 个答案:

答案 0 :(得分:33)

这看起来像是操作员错误的情况。我的webpack.config.js结构不正确。具体来说,我需要将加载程序详细信息放在module部分中:

module.exports = {
  entry: './src/admin/client/index.jsx',
  output: {
    filename: './src/admin/client/static/js/app.js'
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel',
        exclude: /node_modules/,
        query: {
          optional: ['runtime']
        }
      }
    ],
    resolve: {
      extensions: ['', '.js', '.jsx']
    }
  }
};

答案 1 :(得分:15)

我修复了同样的问题,包括 es2015 反应 预设,然后将它们添加到webpack.config.js文件中。< / p>

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

如本文所述:https://www.twilio.com/blog/2015/08/setting-up-react-for-es6-with-webpack-and-babel-2.html

我的完整webpack.config.js文件:

module.exports = {
  context: __dirname + "/src",
  entry: './main',
  output: {
    path: __dirname + "/build",
    filename: "bundle.js"
  },
  module: {
    loaders: [
      { 
        test: /\.js$/,
        exclude: /node_modules/,
        loader: "babel-loader",
        query: {
          presets: ['es2015', 'react']
        }
      }
    ],
    resolve: {
      extensions: ['.js', '.jsx']
    }
  }
};

答案 2 :(得分:10)

你的babel版本是什么?如果babel版本高达6 +。你需要识别预设&#39; es2015&#39;和&#39;反应&#39;像这样

module: {
  loaders: [
    {
      test: /\.jsx?$/,
      exclude: /(node_modules|bower_components)/,
      loader: 'babel', // 'babel-loader' is also a legal name to reference
      query: {
        presets: ['react', 'es2015']
      }
    }
  ]
}

别忘了安装这些模块:

npm install babel-loader babel-core babel-preset-es2015 babel-preset-react --save-dev