29

我有这个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
哈希:2a9a40224beb025cb433
版本:webpack 1.10.5
时间:44ms
   [0] ./src/admin/client/index.jsx 0 字节 [已建] [失败]

./src/admin/client/index.jsx 中的错误
模块解析失败:/project/src/admin/client/index.jsx 第 1 行:意外的保留字
您可能需要适当的加载程序来处理此文件类型。
| 从“反应”导入反应;
| 从'./components/AdminInterface'导入AdminInterface;

我有:

  • webpack全局和本地安装
  • 已安装babel-loader,babel-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

4

3 回答 3

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']
    }
  }
};
于 2015-08-04T02:52:26.697 回答
15

我通过包含es2015react 预设然后将它们添加到 webpack.config.js 文件来解决了同样的问题。

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']
    }
  }
};
于 2015-12-31T14:05:33.550 回答
10

你的babel是什么版本的?如果babel版本是6+的话,需要识别预设的'es2015'和'react'这样

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
于 2016-01-22T08:41:56.477 回答