引入React时,Webpack无法正常工作

The*_*ane 5 javascript reactjs webpack react-jsx webpack-dev-server

我已经按照webpack上的主要教程进行了操作,并且我已经启动并运行了服务器.当我更改文件时,它会在保存时更新,一切都很好.然而,我然后介绍了React,这一切都出了问题.

首先,我在浏览器中收到此错误:

Unexpected token <
You may need an appropriate loader to handle this file type.
Run Code Online (Sandbox Code Playgroud)

这指向我的entry.js文件中的第4行:

var CommentBox = React.createClass({
  render: function() {
    return (
        <div className="commentBox">
          Hello, world! I am a CommentBox.
        </div>
    );
  }
});
ReactDOM.render(
    <CommentBox />,
    document.getElementById('content')
);
Run Code Online (Sandbox Code Playgroud)

这是index.html

<html>
<head>
    <meta charset="utf-8">
</head>
<body>

    <div id ="content"></div>
<script type="text/javascript" src="bundle.js" charset="utf-8"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

webpack.config.js:

module.exports = {
  entry: "./entry.js",
  output: {
    path: __dirname,
    filename: "bundle.js"
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'jsx-loader?insertPragma=React.DOM&harmony'
      }
    ]
  },
  externals: {
    'react': 'React'
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  }
};
Run Code Online (Sandbox Code Playgroud)

如果我将entry.js文件更改为仅包含:

document.write(require("./content.js"));
Run Code Online (Sandbox Code Playgroud)

它生成我目前在content.js文件中的内容:

module.exports = "this is working";
Run Code Online (Sandbox Code Playgroud)

因此,它与react/jsx等有关.任何人都有这个解决方案吗?我已经在网上看过其他人这个问题,但到目前为止给出的解决方案并没有对我有用.

小智 2

网页包和jsx-loader

webpack.config.js

module.exports = {
  entry: './app.js',
  output: {
    path: __dirname,
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      test: /\.js/,
      loader: 'jsx-loader'
    }]
  }
}
Run Code Online (Sandbox Code Playgroud)

应用程序.js

var React = require('react');

var App = React.createClass({
  render: function() {
    return <h1>Hello World</h1>
  }
})

React.render(<App/>, document.getElementById('app'))
Run Code Online (Sandbox Code Playgroud)

和简单的index.html文件,其中包含<div>

可能您想使用带有 ES6 语法的 React(React webpack 和 babel),所以:我希望我的文章对您有用。

更新:

正如 FakeRainBrigand所说的jsx-loader那样,如果你尝试使用 babel-loader 而不是jsx-loader

谢谢