I'm trying to introduce React with ES6 into my app, which is built with Gulp. I can get React working alone, and ES6 working alone. But trying to import crashes my Gulp build. Gulp's error is:
Line 14: Illegal import declaration
My HTML page includes React and the built JS file:
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.12.2/react.min.js"></script>
<script src="js/app.js"></script>
app.js looks like this:
import {Child} from './child.js';
var Parent = React.createClass({
render: function(){
const y = 3; //es6 works
return (
<div>
<div> This is the parent {y}. </div>
<Child name="child"/>
</div>
)
}
});
React.render(<Parent />, document.getElementById('container'));
child.js is in the same directory and looks like this:
var Child = React.createClass({
render: function(){
return (
<div>
and this is the <b>{this.props.name}</b>.
</div>
)
}
});
export default Child;
The part of my Gulp file that compiles ES6 with Babel:
gulp.task('babel', function(){
gulp.src('js/app.js')
.pipe(react())
.pipe(babel({
presets: ['es2015']
}))
.pipe(gulp.dest('dist/js'));
});
What am I missing/doing wrong that is preventing me from using import?
You have to apply the es6module option to gulp-react to allow for importing of modules:
.pipe(react({
es6module: true
}))
Then, fix your import statement. Since Child is exported as default, import it like this:
import Child from './child.js';
Note: gulp-react was deprecated in favor of gulp-babel so I suggest using that instead if you're already using it for es2015. use gulp-babel instead and install the react preset for Babel:
npm install --save-dev babel-preset-react
Finally, apply it to gulp-babel:
presets: ['es2015', 'react']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With