Reputation: 3123
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
?
Upvotes: 3
Views: 2334
Reputation: 57934
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']
Upvotes: 3