繁体   English   中英

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

[英]Webpack with babel-loader not recognizing import keyword

我有这个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

这看起来像是操作员错误的情况。 我的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']
    }
  }
};

我通过包含es2015反应 预设然后将它们添加到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']
    }
  }
};

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

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

暂无
暂无

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

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