使用 babel 将 React JSX 组件转换为 ES5

Convert React JSX component to ES5 usign babel

我正在尝试将 JSX React 组件转换为可在 ES5 中使用的 React 组件。

所以我在我的存储库的根目录下添加了带有 npm 的 babel。

{
  "name": "xxx",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "ssh://xxx"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-react-app": "^3.1.2"
  },
  "devDependencies": {
    "@babel/cli": "^7.12.10",
    "@babel/core": "^7.12.10",
    "@babel/plugin-transform-react-jsx": "^7.12.12",
    "babel-core": "^7.0.0-bridge.0"
  }
}

然后我这样执行watcher

npx babel --watch Components\ --out-dir React\ --presets react-app/prod

我原来的 React JSX 组件是这样的:

import React from 'react';
import Button from '@material-ui/core/Button';

const NeoFormulaire = () => {
  return (
    <Button color='secondary' variant='outlined'>
      Bouton test 2
    </Button>
  );
};

export default NeoFormulaire;

转译后的是这样的:

import React from 'react';
import Button from '@material-ui/core/Button';

var NeoFormulaire = function NeoFormulaire() {
  return React.createElement(
    Button,
    { color: 'secondary', variant: 'outlined' },
    'Bouton test 2'
  );
};

export default NeoFormulaire;

有些部分发生了变化,但不是全部,我还必须做些什么来转译 importexport 以及我将来会使用的任何挂钩?

Babel 不进行模块捆绑,因为您需要像 Webpack or Rollup 这样的模块捆绑器。他们与 Babel 集成,让 Babel 处理各种 JavaScript 转换,而捆绑器处理模块转换并将事物捆绑在一起成少量文件。

FWIW,https://create-react-app.dev/ 将使用 Webpack、Babel、ESLint、TypeScript 为您构建完整的项目框架,如果您需要,... CRA 会为您管理您的项目,但您可以随时“ eject" 以获得您可以调整的硬编码配置文件。

自动化程度较低,但 Rollup 有一个 quick start and instructions for integrating with Babel and adding peer dependencies 像 React。