JimYang
JimYang

Reputation: 15

import statements fail on react

I'm learning React, and I have a php project set up like this:

In the head of index.php I load:

<script type="text/javascript" src="js/libs/react.js"></script>
<script type="text/javascript" src="js/libs/react-dom.js"></script>
<script type="text/javascript" src="js/libs/browser.min.js"></script>

and at the bottom:

<script type="text/babel" src="jsx/index.jsx"></script>
<script> 
        window.onload=function(){ 
         site.init();
         }</script>
</script>

I'm not doing any transpiling. Everything runs fine on Apache+Firefox.

Then I wanted to add some transitions, like images fading in and out when clicking a button instead of just switching. So I:

1- downloaded react transition from here: https://github.com/reactjs/react-transition-group

2- added the content of its src folder to js, which now looks like this:

js/
../<some vanilla.js files>
../libs/
../libs/react.js
../libs/react-dom.js
../libs/browser.min.js
../libs/react-transition-group/
......./react-transition-group/index.js
......./react-transition-group/CSSTransitionGroup.js
......./react-transition-group/CSSTransitionGroup.js
......./react-transition-group/TransitionGroup.js

3- loaded index.js like this:

Now, on Chrome, I get this error when I run the site:

index.js:1 Uncaught SyntaxError: Unexpected token import

On Firefox:

SyntaxError: import declarations may only appear at top level of a module  index.js:1

Any idea about what am I missing?

Thanks

Upvotes: 0

Views: 917

Answers (2)

JimYang
JimYang

Reputation: 15

As Andy Ray stated here http://blog.andrewray.me/webpack-when-to-use-and-why, it looks like I was doing things the old way; the wheel has been reinvented and the php-webpacker-of-sorts I use seems to start to lag behind.

It seems that I was unfortunately lucky to use a set of libraries that posed no conflict when imported just as <script src=library.js>, and react-transition dispelled that illusion. Following dejakob advice, I've integrated transpiling in the process and, at least for the moment, things seem to work seamlessly again.

Thanks

Upvotes: 0

dejakob
dejakob

Reputation: 2102

to use import, you should not use the babel polyfill, but transpile the code with babel. Therefore, it's highly encouraged to use webpack in your react project with a babel plugin.

This blog might help you further with setting up a react/webpack/babel project: https://scotch.io/tutorials/setup-a-react-environment-using-webpack-and-babel

Upvotes: 1

Related Questions