【问题标题】:Webpack error: "You may need an appropriate loader to handle this file type"Webpack 错误:“您可能需要适当的加载器来处理此文件类型”
【发布时间】:2017-03-24 06:28:20
【问题描述】:

我一直在使用 react 设置一个个人项目,但遇到一个我无法找到答案的错误。 Webpack 不断给出以下错误信息:

ERROR in ./app/components/Home.js
Module parse failed: 
/Users/LandonKoo/projects/lktheprogrammer/app/components/Home.js Unexpected token (5:10)
You may need an appropriate loader to handle this file type.
| class Home extends Component{
|   render() {
|     return (<h1>Hey!!!! Home!!</h1>);
|   }
| }
@ ./app/src/index.js 11:12-44

package.json:

{
  "name": "lktheprogrammer",
  "version": "1.0.0",
  "description": "Blog for LK the Programmer",
  "main": "index.js",
  "scripts": {
  "watch": "webpack -d --watch",
  "production": "webpack -p"
},
"author": "Landon Koo <landonkoo0207@gmail.com>",
"license": "ISC",
"devDependencies": {
  "babel-core": "^6.24.0",
  "babel-loader": "^6.4.1",
  "babel-preset-es2015": "^6.24.0",
  "babel-preset-react": "^6.23.0",
  "html-webpack-plugin": "^2.28.0",
  "webpack": "^2.3.1",
"webpack-dev-server": "^2.4.2"
},
"dependencies": {
  "babel-core": "^6.24.0",
  "babel-loader": "^6.4.1",
  "react": "^15.4.2",
  "react-bootstrap": "^0.30.8",
  "react-dom": "^15.4.2",
  "react-router": "^2.8.1"
}
}

webpack.config.js:

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

var BUILD_DIR = path.resolve(__dirname, 'app/dist');
var APP_DIR = path.resolve(__dirname, 'app/src');

var config = {
  entry: APP_DIR + '/index.js',
  output: {
    path: BUILD_DIR,
    filename: 'index_bundle.js'
  },
  module : {
    loaders : [
      {
        test : /\.(js|jsx)$/,
        include : APP_DIR,
        exclude : /node_modules/,
        loader : 'babel-loader'
      }
    ]
  }
};

module.exports = config;

为此我被困了好几个小时。任何评论将不胜感激! 谢谢!

【问题讨论】:

    标签: reactjs webpack babeljs


    【解决方案1】:

    你需要创建 .babelrc 文件

    //./.babelrc
    {
        "presets":[
            "es2015", "react"
        ]
    }
    

    或将预设指定为加载器选项

    {
        test : /\.(js|jsx)$/,
        include : APP_DIR,
        exclude : /node_modules/,
        loader : 'babel-loader',
        query: { presets: ['es2015', 'react']}
    }
    

    【讨论】:

    • 我的 .babelrc 文件和你提到的完全一样。我很抱歉把它漏掉了。你能想到造成这种情况的任何其他原因吗?无论如何,感谢您的回复! :)
    • 我想通了。原来我把组件放在了错误的地方。还是谢谢!
    • @LandonKoo 你能解释一下你是如何解决这个问题的。我也陷入了类似的境地。
    【解决方案2】:

    也使用“react-hot”加载器, 请参考https://github.com/babel/babel-loader/issues/173

    【讨论】:

      【解决方案3】:

      对我来说,我的 jsx 文件有大写的 JSX 扩展名

      测试:/.(js|jsx)$/, 找不到大写的 JSX,所以需要变成 测试:/.(js|jsx|JSX|JS)$/,

      或者将大写的 JSX 文件扩展名重命名为小写的 jsx 也可以

      【讨论】:

        猜你喜欢
        • 2016-06-02
        • 2019-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-08
        • 1970-01-01
        相关资源
        最近更新 更多