Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Top level javascript imports - Redux

I'm trying to learn redux and I've run into an error. I only have two files, an index.html file and a main.js file, there are links to the jquery and redux cdns in the html file. I've only gotten to 2.3 in the redux tutorial(http://redux.js.org/docs/basics/Store.html) and am stuck. I have

import {createStore} from 'redux';

at the top of my main.js file, but when I load the application, I get an error pointing to line above saying

SyntaxError: import declarations may only appear at top level

What is a 'top level import declaration'?

Here is a gist to my code if that helps. https://gist.github.com/austincarvey/6e6c8fdc2640b0f9bbfb

like image 558
user3813472 Avatar asked Dec 31 '15 00:12

user3813472


2 Answers

The import directive is not recognised by web browsers. It's used at the compilation stage, to tie together different source files and third party modules into a single web bundle. If that doesn't make sense, then I highly recommended learning Babel and either Webpack or Browserify. Babel transpiles ES6 and React syntax to browser friendly ES5 code, whilst Webpack/Browserify bundle your modules.

For now however, if you just want to get on with learning Redux, you can simply remove the import statement and instead use the global variable Redux exposed by the redux CDN script in your gist. i.e.

var store = Redux.createStore(counterReducer);
like image 55
David L. Walsh Avatar answered Oct 26 '22 08:10

David L. Walsh


import is used when you are including a file via es6 modules in a context that supports them (Browserify/Webpack/etc, future versions of browsers).

Since you are including the Redux lib via <script> tag, that takes care of including Redux in the global scope.

In the case of your gist, if you erase line one and change the createStore invocation to Redux.createStore on 29, everything should work.

like image 23
max Avatar answered Oct 26 '22 08:10

max