开发者问题收集

关于c#:Webpack 使用 react 时出现错误

2015-08-15
22791

我正在尝试根据此 教程 配置 webpack,但仍然出现相同的错误。我在调试这 2 条消息时遇到了麻烦:

ERROR in ./app.js
Module parse failed: /path/react/react-webpack-babel/app/app.js Line 1: Unexpected reserved word
You may need an appropriate loader to handle this file type.
| import React from "react";
| import Greeting from "./greeting";
|

ERROR in ./index.html
Module parse failed: /path/react/react-webpack-babel/app/index.html Line 1: Unexpected token <
You may need an appropriate loader to handle this file type.
| <!DOCTYPE html>
| <html>
|

这是我的 webpack.configure.js

module.exports = {
  context: __dirname + '/app',
  entry: {
    javascript: "./app.js",
    html: "./index.html"
  },
  output: {
    filename: 'app.js',
    path: __dirname + '/dist'
  },
  loaders: [
    {
      test: /\.js$/,
      exclude: /node_modules/,
      loaders: ['babel-loader']
    },
    {
      test: /\.jsx$/,
      loaders: ['babel-loader']
    },
    {
      test: /\.html$/,
      loader: "file?name=[name].[ext]"
    }
  ]
}

这是我的 react 组件

app/greeting.js

import React from "react/addons";

export default React.createClass({
  render: function() {
    return (
      <div className="greeting">
        Hello, {this.props.name}!
      </div>
    );
  },
});

app/app.js

import React from "react/addons";
import Greeting from "./greeting";

React.render(
  <Greeting name="World"/>,
  document.body
);

app/index.html

<!DOCTYPE html>
<html>

  <head>
    <meta charset="utf-8">
    <title>Webpack + React</title>
  </head>

  <body></body>

  <script src="app.js"></script>

</html>

以防万一,这是我的带有依赖项的 package.json

{
  "name": "project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "private": true,
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Me",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^5.8.22",
    "babel-loader": "^5.3.2",
    "file-loader": "^0.8.4",
    "webpack": "^1.11.0"
  },
  "dependencies": {
    "react": "^0.13.3"
  }
}
2个回答

loaders 选项应嵌套在 module 对象中,如下所示:

module.exports = {
  context: __dirname + '/app',
  entry: {
    javascript: "./app.js",
    html: "./index.html"
  },
  output: {
    filename: 'app.js',
    path: __dirname + '/dist'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loaders: ['babel-loader']
      },
      {
        test: /\.jsx$/,
        loaders: ['babel-loader']
      },
      {
        test: /\.html$/,
        loader: "file?name=[name].[ext]"
      }
    ]
  }
};

我还在末尾添加了一个缺失的分号 ;)

Almouro
2015-08-16

当我使用语法

import Component from './components/component';

导入时,我收到模块解析错误。要修复它,我必须指定 .jsx ,然后它就可以正常工作了

import Component from `./components/component.jsx`. 

这根本不是配置错误。我在使用带有热加载器的 babel 6。

Daniel Lizik
2016-03-27