使用Webpack和Babel,你可能需要一个合适的加载器来处理这个文件types

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

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

这是我的Webpackconfiguration看起来像:

 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); }); 

我所有的index.js文件正在导入反应,但似乎像'babel-loader'不工作。

我正在使用'babel-loader'6.0.0。

您需要安装es2015预设:

 npm install babel-preset-es2015 

然后configurationbabel-loader

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

确保你已经安装了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" }, 

现在在你的webpackconfiguration中configurationbabel-loader

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

将一个.babelrc文件添加到您的项目的根节点模块是:

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

更多信息:

  • babeljs.io – 使用webpack的babel

  • babeljs.io – docs.babelrc

  • react-webpack-cookbook – configuration与webpack反应

  • 一个react-webpack例子的回购

如果您使用的是Webpack> 3,那么您只需要安装babel-preset-env ,因为此预设占了es2015,es2016和es2017。

 var path = require('path'); let webpack = require("webpack"); module.exports = { entry: { app: './app/App.js', vendor: ["react","react-dom"] }, output: { filename: 'bundle.js', path: path.resolve(__dirname, '../public') }, module: { rules: [{ test: /\.jsx?$/, exclude: /node_modules/, use: { loader: 'babel-loader?cacheDirectory=true', } }] } }; 

这从我的.babelrc文件中获取它的configuration:

 { "presets": [ [ "env", { "targets": { "browsers":["last 2 versions"], "node":"current" } } ],["react"] ] }