Chrome 61: Unexpected token import

前端 未结 3 1228
慢半拍i
慢半拍i 2020-12-09 09:37

Running Chrome 61 which is supposed to support module loading with import.

Indeed Paul\'s demo works for me. However, when I try it myself I get a JS er

相关标签:
3条回答
  • 2020-12-09 09:49

    For those of you who want to know exactly what worked for me, it was kind of a combination of a couple answers from above. I also had to enable the ES6 import capabilities of Chrome by typing chrome://flags in the URL bar and searching for "import".

    First the HTML:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Testing JavaScript Stuff</title>
    </head>
    <body>
        <script type="module">
            import { circleArea, squareArea } from './CalcArea.js';
    
            console.log(circleArea(2));
            console.log(squareArea(2));
        </script>
    </body>
    </html>
    

    So as you can see just add the type "module" to your script tag, then below you do the import. For my test the CalcArea.js file is this:

    const circleArea = r => 3.14 * (r ** 2);
    
    const squareArea = s => s * s;
    
    export {circleArea, squareArea};
    
    0 讨论(0)
  • 2020-12-09 09:59

    Finally... figured it out. chrome://flags search for import enable ES6 import syntax. Restart Chrome. Be happy.

    0 讨论(0)
  • 2020-12-09 10:01

    That should be <script type=module src=test.js>. The entire syntax is subtly changed in module scripts (import and export are allowed, as well as strict mode being mandatory).

    0 讨论(0)
提交回复
热议问题