简体   繁体   中英

Convert React JSX component to ES5 usign babel

I am trying to transpile a JSX React Component to a React component usable in ES5.

So I added babel with npm at the root of my repository.

{
  "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"
  }
}

Then I execute the watcher like this

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

My original React JSX component is like this:

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;

And the transpiled one is like this:

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;

Some parts changed but not everything, what must I do more to transpile import , export and any future hooks I will use?

Babel doesn't do module bundling, for that you'd want a module bundler like Webpack or Rollup . They integrate with Babel, letting Babel handle the various JavaScript transforms while the bundlers handle module transforms and bundling things together into a small number of files.

FWIW, https://create-react-app.dev/ will do a full project skeleton for you with Webpack, Babel, ESLint, TypeScript if you want it, ... CRA manages your project for you, but at any time you can "eject" to get hardcoded config files you can tweak.

Less automated, but Rollup has a quick start and instructions for integrating with Babel and adding peer dependencies like React.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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