1

I have the following "website" (feel free to skim, the only important part here is the import statement):

<html>
    <head>  
    </head>
    <body> 
        <script>

            import * as mathSolverModule from 'components/mathSolverModule';

            var result = mathSolverModule.add(2+2); 

            document.write(result); 
        </script>
    </body>
</html>

The mathSolverModule file is this:

export function multiply(x, y) {
    return x * y; 
}

export function add(x, y) {
    return x + y; 
}

Predictably, I get the following error when running this in latest Chrome:

Uncaught SyntaxError: Unexpected token import

What is the easiest way to fix this? Is there some script I can include to "just make it work" or do I need SystemJS/WebPack/etc and HAVE to compile into something else (ES5, as I understand it)?


Edit, I tried:

<html>
    <head>  
        <script src = "https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.14.0/babel.min.js"></script> 
    </head>
    <body> 
        <script type="text/babel">

            import * as mathSolverModule from 'components/mathSolverModule';

            var result = mathSolverModule.add(2+2); 

            document.write(result); 
        </script>
    </body>
</html>

and I get the following:

Uncaught ReferenceError: require is not defined

VSO
  • 11,546
  • 25
  • 99
  • 187
  • 1
    You can't add new keywords to the language. You have to use a transpiler. – JJJ Sep 24 '16 at 21:19
  • 1
    See [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Browser_compatibility). ES != JS, use a transpiler – Andrew Li Sep 24 '16 at 21:20
  • Damn, that sucks. Thanks. – VSO Sep 24 '16 at 21:21
  • 1
    If it helps, you can transpile on the fly with some libraries by marking the code with ` – JJJ Sep 24 '16 at 21:24
  • That would be awesome and help a lot, but I get the following "Uncaught ReferenceError: require is not defined", figuring it out now. Iirc, require is precursor to the import syntax, but I thought Chrome should be able to use it. – VSO Sep 24 '16 at 21:45

0 Answers0