Snipzwolf Snipzwolf - 12 days ago 6
React JSX Question

Requiring modules from requirejs (with babeljs plugin) in es6 scripts

I'm trying to use RequireJS babel plugin along with ReactJS to make a simple class in es6 but cant figure out how to Import or Require Reacts library from RequireJS while also exporting the class to use in another script.

Below is the jsbin of what i've done so far but currently it errors when i get to the es6 class because the export is inside the require call but if i remove the require call React.Component wont exist.

HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.2/require.min.js"></script>
<script src="https://output.jsbin.com/guvalasowi.js"></script>
<title>JS Bin</title>
</head>
<body>
<div id="a-div"></div>
</body>
</html>


RequireJS Config

require({
paths: {
es6: "https://cdn.rawgit.com/mikach/requirejs-babel/master/es6",
babel: "https://cdn.rawgit.com/mikach/requirejs-babel/master/babel-5.8.34.min",
react: "https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-with-addons.min",
reactDOM: "https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-dom.min",
test: "https://output.jsbin.com/sahudexegu"
}
});
require(['es6!test', 'reactDOM'], function(test, ReactDOM){
ReactDOM.render(
table,
document.getElementById("a-div")
);
});


Test Module (es6 class)

require(['react'], function(React){
class Welcome extends React.Component {
render() {
return <h1>Hello</h1>;
}
};

export {Welcome};
});


tl;dr: How do you require modules from requirejs when inside es6 scripts and still export a class object?

Answer

First, to answer your main question, the export can done like this:

import React from 'react';

class Welcome extends React.Component {
    render() {
         return (
            <h1>Hello</h1>
         );
    }
}

export default Welcome

The usage of the component (had some trouble with your ReactDOM include as it was):

requirejs.config({
  paths: {
    'es6': "bower_components/requirejs-babel/es6",
    'babel': "babel-5.8.34.min",
    'react': 'https://unpkg.com/react@15.3.2/dist/react',
    'react-dom': 'https://unpkg.com/react-dom@15.3.2/dist/react-dom',
    'Welcome': "Welcome"
  }
});


requirejs(['es6!test', 'react', 'react-dom'], function(test,  React, ReactDOM) {

  var Welcome = test.default;

  ReactDOM.render(
    <Welcome />,
    document.getElementById("a-div")
  );

});
Comments