当前位置: 首页 > 知识库问答 >
问题:

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

常朗
2023-03-14

我试图使用Babel的Webpack编译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);
});

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

我正在使用“babel loader”6.0.0。

共有3个答案

辛成周
2023-03-14

如果您正在使用Webpack

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文件中获取其配置:

{
    "presets": [
        [
            "env",
            {
                "targets": {
                    "browsers":["last 2 versions"],
                    "node":"current"
                }
            }
        ],["react"]
    ]
}
冀萧迟
2023-03-14

确保已安装es2015 babel预设。

一个例子package.json开发依赖是:

"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"
},

现在在您的网页配置中配置babel loader:

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

将. babelrc文件添加到项目的根目录中,其中的节点模块是:

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

更多信息:

>

  • babeljs.io-使用Babel与webpack

    babeljs.io-docs on.babelrc

    react webpack cookbook-配置react with webpack

  • 籍永安
    2023-03-14

    您需要安装es2015预设:

    npm install babel-preset-es2015
    

    然后配置巴别塔加载器:

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