“您可能需要一个合适的加载程序来处理这种文件类型”与Webpack和Babel

我正在尝试将Webpack与Babel一起使用来编译ES6资产,但是我收到以下错误消息:

You may need an appropriate loader to handle this file type.
| import React from 'react';
| /*
| import { render } from 'react-dom'

以下是我的 Webpack 配置的样子:

var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: './index',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/dist/'
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      }
    ]
  }
}

以下是使用 Webpack 的中间件步骤:

var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var config = require('./webpack.config');

var express = require('express');
var app = express();
var port = 3000;

var compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath
}));

app.get('/', function(req, res) {
  res.sendFile(__dirname + '/index.html');
});

app.listen(port, function(err) {
  console.log('Server started on http://localhost:%s', port);
});

我的索引.js文件所做的就是导入react,但似乎“babel-loader”不起作用。

我使用的是'babel-loader' 6.0.0。


答案 1

您需要安装预设:es2015

npm install babel-preset-es2015

,然后配置:babel-loader

{
    test: /\.jsx?$/,
    loader: 'babel-loader',
    exclude: /node_modules/,
    query: {
        presets: ['es2015']
    }
}

答案 2

确保已安装 es2015 babel 预设

一个示例 package.json devDependencies 是:

"devDependencies": {
  "babel-core": "^6.0.20",
  "babel-loader": "^6.0.1",
  "babel-preset-es2015": "^6.0.15",
  "babel-preset-react": "^6.0.15",
  "babel-preset-stage-0": "^6.0.15",
  "webpack": "^1.9.6",
  "webpack-dev-middleware": "^1.2.0",
  "webpack-hot-middleware": "^2.0.0"
},

现在在你的 webpack 配置中配置 babel-loader

{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }

.babelrc 文件添加到节点模块所在的项目根目录:

{
  "presets": ["es2015", "stage-0", "react"]
}

更多信息: