用babel编译jsx文件

babel可以把jsx文件编译成es5文件,也可以把es6编译成es5,还支持其它的各种语言编译。这篇文章介绍babel的jsx -> js文件的编译过程。首先写一个jsx文件:

const a = <div />

const b = (
  <div
    foo='hello'
    bar={baz}>
    <span>42</span>
  </div>
)

安装babeljsx的插件(babel-plugin-transform-react-jsx · Babelbabel/packages/babel-plugin-transform-react-jsx at master · babel/babel · GitHub):

$ npm install babel-plugin-transform-react-jsx

编译jsx文件:

$ babel --plugins transform-react-jsx script.js

编译后的输出:

const a = React.createElement('div', null);

const b = React.createElement(
  'div',
  {
    foo: 'hello',
    bar: baz },
  React.createElement(
    'span',
    null,
    '42'
  )
);

在线的compiler:

参考资料:

My Github Page: https://github.com/liweinan

Powered by Jekyll and Theme by solid

If you have any question want to ask or find bugs regarding with my blog posts, please report it here:
https://github.com/liweinan/liweinan.github.io/issues