3

I add babel compiler in my page to use ES6 syntax by below:

<script src="babel.min.js"></script>

And create a simple module in M.js as below:

export var M={
    p:3
};

And use it in my page:

<script type="text/babel">
    import {M} from './M';
    console.log(M.p);
</script>

But meet below error in console:

Uncaught ReferenceError: require is not defined

How can I make module works in browser? Does babel.js support module or not? If not, if there's other way I can make ES6 module syntax works in browser.

gloomyson
  • 171
  • 2
  • 5
  • You have to use a module loader along with Babel. – gcampbell Jul 12 '16 at 10:06
  • @gcampbell What kind of module loader should I use? Do you mean I need to add "" in my page, right? – gloomyson Jul 12 '16 at 10:11
  • Generally you'd compile your code in Node with something like Browserify, then load that in a script tag, rather than compiling in your browser itself with `text/babel`. – loganfsmyth Jul 12 '16 at 16:41
  • instead try `import {M} from './M.mjs'` and rename your M file with extension `.mjs`. This fixed the problem. Also your first script that gets loaded by the html should look something like `` – Got To Figure Nov 04 '22 at 14:59
  • @GotToFigure still says 'require is not defined' – Userx10xC Jan 05 '23 at 10:27

2 Answers2

-2

Use a dynamic ES Module loader like SystemJS and the Babel Plugin

Doug
  • 14,387
  • 17
  • 74
  • 104
-2

Have you tried setting the data-plugin attribute to "transform-es2015-modules-umd"? As below?

<script data-plugins="transform-es2015-modules-umd" type="text/babel">
    import M from './M';
    console.log(M.p);
</script>
mqueirozcorreia
  • 905
  • 14
  • 33