简体   繁体   English

webpack / react / babel不编译JSX

[英]webpack/react/babel doesn't compile JSX

I know there are a lot of similar questions but I didn't found the solution and some of them are old so they don't apply. 我知道有很多类似的问题,但我没有找到解决方案,其中一些是旧的,所以他们不适用。

I've created a Webpack environmental for react but doesn't compile JSX syntax. 我已经为反应创建了一个Webpack环境,但是没有编译JSX语法。

I'm using: 我正在使用:

"@babel/core": "^7.1.6",
"@babel/preset-env": "^7.1.6",
"@babel/preset-react": "^7.0.0",
"react": "^16.7.0",
"react-dom": "^16.7.0",

In my babel.config.js I have: 在我的babel.config.js我有:

  ...
  'presets': [
    [
      '@babel/preset-env',
      {
        'targets': {
          'chrome': 61,
        },
        'modules': false,
        'useBuiltIns': 'usage'
      },
      '@babel/preset-react'
    ]
  ],
  ...

I can compile react code like this: 我可以像这样编译反应代码:

import React from 'react'
import ReactDOM from 'react-dom'
require('./scss/main.scss')

const e = React.createElement

class LikeButton extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      liked: false
    }
  }

  render () {
    if (this.state.liked) {
      return 'You liked this.'
    }

    return e(
      'button',
      {
        onClick: () => this.setState({
          liked: true
        })
      },
      'Like'
    )
  }
}

const domContainer = document.querySelector('#like_button_container')
ReactDOM.render(e(LikeButton), domContainer)

but when I tried to use JSX 但是当我尝试使用JSX时

const name = 'Name';
const element = <h1>Hello, {name}</h1>;

ReactDOM.render(
  element,
  document.getElementById('root')
);

it complain about the < of the h1 它抱怨<所述的h1

here my repo: 我的回购:

https://github.com/sebalaini/test https://github.com/sebalaini/test

Move your @babel/preset-react outside your config for @babel/preset-env (move it outside the array), like this: @babel/preset-react到配置之外@babel/preset-env (将其移到数组外),如下所示:

presets: [
  ["@babel/preset-env", {...}],
  "@babel/preset-react",
]

@babel/preset-react should be on the same level (top level for presets ) as your @babel/preset-env . @babel/preset-react应与@babel/preset-env处于同一级别( presets顶级)。

const element in your code is not a valid React component. 代码中的const element不是有效的React组件。 You need to return a function and always start component names with a capital letter. 您需要返回一个函数,并始终使用大写字母启动组件名称。

// Always import React at the top of the file!
import React from 'react';

function Person(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Person name="Name of the person" />;

ReactDOM.render(
  element,
  document.getElementById('root')
);

More on components here: https://reactjs.org/docs/components-and-props.html 有关组件的更多信息,请访问: https//reactjs.org/docs/components-and-props.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM