首页 文章

webpack babel loader无法编译jsx

提问于
浏览
3

我'm trying to run a simple boilerplate for react + webpack + hot module replacement. But I'实际上卡在babel / jsx步骤并需要帮助 . 我正在关注this article .

目前我有:

webpack.config.js

module.exports = {
  context: __dirname + "/app",
  entry: "./app.js",

  output: {
    filename: "app.js",
    path: __dirname + "/dist",
  },

  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loaders: ["babel-loader"],
      }
    ],
  },
}

app/app.js

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

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

app/greetings.js

import React from "react";

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

这在 package.json

"devDependencies": {
    "babel-core": "^6.18.0",
    "babel-loader": "^6.2.7",
    "webpack": "^1.13.3"
  },
  "dependencies": {
    "react": "^15.3.2"
  }

当我在控制台中运行 webpack 时,正如教程所说,它应该运行webpack(和下面的babel)并捆绑整个应用程序,但它没有 - 相反,它会抛出以下错误:

$ webpack
Hash: 9a56cc72acac2de6f40c
Version: webpack 1.13.3
Time: 543ms
    + 1 hidden modules

ERROR in ./app.js
Module build failed: SyntaxError: C:/Users/abc/Tests/webpack-react-hmr/app/app.js: Unexpected token (7:2)

   5 |
   6 | React.render(
>  7 |   <Greeting name="World"/>,
     |   ^
   8 |   document.body
   9 | );
  10 |

我知道问题是什么,但肯定的是,webpack无法理解JSX语法 . 也许this part of the tutorial错误或过时了:

幸运的是,Babel加载器支持转换ES2015和JSX,这意味着我们可以使用单个加载器而不需要babel-loader和jsx-loader . 我们可以使用以下命令安装babel加载程序:npm install babel-loader --save-dev

我该怎么做才能修复webpack / jsx / babel设置?

1 回答

  • 1

    您需要使用babel预设来编译 react 和其他ES6,ES7功能 .

    所需预设列表:

    • 最新

    • 做出反应

    • 阶段-0

    将此文件添加为 .babelrc 到您的根目录 .

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

    并执行此安装

    npm install --save-dev babel-preset-latest babel-preset-react babel-preset-stage-0
    

    现在,运行webpack . 它应该工作!

相关问题