How to translate React ES6 classes using Grunt + Browserify + Reactify?

I want to use the new ES6 React classes that were introduced with React v0.13, but I cannot get it to compile correctly. Say I have the following React component defined in the syntax of a new class:

(function() { 'use strict'; import React from 'react'; class _UserDashboard extends React.Component { render() { return( <div className="user-dashboard"> <Books /> </div> ); } } export const UserDashboard = React.createClass(_UserDashboard.prototype); }()); 

The problem that I am facing is that during compilation using Grunt and Browserify and Reactify , Reactify gives an error message when it finds the import keyword:

ReactifyError: / Users / **** / Sites / *** / assets / js / components / UserDashboard.jsx: Analysis error: line 7: Unexpected reserved word while analyzing the file: / Users / **** / Sites / * *** / assets / js / components / UserDashboard.jsx

The problem here seems to be related to using Reactify reactive tools, see here and here . But I'm not sure if it is possible to enable the es6module parameter in Reactify.

I tried these two options to no avail:

 ... transform: [[ 'reactify', {'es6module': true} ]] ... 

and

 ... transform: [[ 'reactify', {'es6':true, 'es6module':true} ]] ... 

Does anyone know how to do this?

+6
source share
2 answers

You can do all this with Babel and babelify (the corresponding Browserify plugin).

Babel itself is an ES6 + transporter for ES5, but it comes with first class JSX support :

JSX and React

Babel works great with React, with its built-in JSX translator.

The Browserify conversion will become:

 { "browserify": { "transform": ["babelify"] } } 

Edit: As in Babel 6, many components have been ported to separate preset packages that you will need to install and include in the transform command.

For React and JSX, you'll need babel-preset-react .

For ES6 you will need babel-preset-es2015

Together they can be specified in the conversion.

 transform: [[babelify, { presets: ["react", "es2015"] }]] 
+18
source

Babelify is the best option for my point of view. A little clarification @Dan answer. For babel v 6.0 you need to install 2 presets.

  • ES2015
  • To react

with something similar to npm install --save-dev babel-preset-react and npm install --save-dev babel-preset-es2015 , and then specify this in the babelify settings using: transform: [[babelify, {presets: ["es2015", "react"]}]]

And if in the code you use, for example, some of the latest responsive functions, for example ...other , you also need to add a stage-0 preset.

+4
source

Source: https://habr.com/ru/post/985018/


All Articles