Babel.js using Import and Export not working

babeljs, export, import, javascript

Solution

Babel cannot perform client-side transpiling of modules, or rather it is not universally supported by browsers. In fact, unless you use a plugin, Babel will transform `import` into `require()`.

If I run the following code:

<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
    <script defer type="text/babel" data-presets="es2015">
        import Mymod from './modules/module';
        Mymod();
    </script>
</head>

I get the following error:

Uncaught ReferenceError: require is not defined

From Babel Docs:

Compiling in the browser has a fairly limited use case, so if you are working on a production site you should be precompiling your scripts server-side. See setup build systems for more information.

Most people choose a pre-compiled module bundler like Webpack or Rollup.

If you really want to perform this client-side, use RequireJS with Babel run via a plugin, though you may need to use AMD syntax.

Native browser support for ES6 modules is still in early stages. But to my knowledge there isn't a preset/plugin available yet for Babel to tell it not to transform `import/export` statements.

Problem

I'm trying to use import and export to create modules and it's not working. I added https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.min.js to the index.html header and tried to import a js file and get an error message saying SyntaxError: import declarations may only appear at top level of a module. What can I possibly be doing wrong? I know I can use require.js but rather use import and export. HTML ``` script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.min.js"></script ``` JS File ``` import Mymodule from './modules/mymodule'; ```

Original source