【问题标题】:Convert React JSX component to ES5 usign babel使用 babel 将 React JSX 组件转换为 ES5
【发布时间】:2021-01-07 11:21:04
【问题描述】:

我正在尝试将 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"
  }
}

然后我像这样执行观察者

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 以及我将使用的任何未来挂钩?

【问题讨论】:

标签: javascript reactjs babeljs


【解决方案1】:

Babel 不做模块捆绑,因为你需要像 WebpackRollup 这样的模块捆绑器。它们与 Babel 集成,让 Babel 处理各种 JavaScript 转换,而捆绑器处理模块转换并将事物捆绑到少量文件中。

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

自动化程度较低,但 Rollup 有一个 quick startintegrating with Babel 的说明,并像 React 一样添加 peer dependencies

【讨论】:

    猜你喜欢
    • 2017-08-24
    • 2017-08-07
    • 2016-08-30
    • 2021-12-18
    • 2020-05-29
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 2020-04-27
    相关资源
    最近更新 更多