簡體   English   中英

瀏覽器中的 ES6 模塊:Uncaught SyntaxError: Unexpected token import

[英]ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import

我是ES6 (ECMAScript 6) 的新手,我想在瀏覽器中使用它的模塊系統 我讀到 Firefox 和 Chrome 支持 ES6,但使用export出現以下錯誤

Uncaught SyntaxError: Unexpected token import

我有一個 test.html 文件

<html>
    <script src="test.js"></script>
<body>
</body>
</html>

和一個 test.js 文件

'use strict';

class Test {

    static hello() {
        console.log("hello world");
    } 
}

export Test;    

為什么?

許多現代瀏覽器現在都支持 ES6 模塊。 只要您使用<script type="module" src="...">導入腳本(包括應用程序的入口點),它就會起作用。

查看caniuse.com了解更多詳情: https : //caniuse.com/#feat=es6-module

您可以在 Google Chrome Beta (61) / Chrome Canary 中試用 ES6 模塊。

Paul Irish 的 ToDo MVC 參考實現 - https://paulirish.github.io/es-modules-todomvc/

我有基本的演示 -

//app.js
import {sum} from './calc.js'

console.log(sum(2,3));
//calc.js
let sum = (a,b) => { return a + b; }

export {sum};
<html> 
    <head>
        <meta charset="utf-8" />
    </head>

    <body>
        <h1>ES6</h1>
        <script src="app.js" type="module"></script>
    </body>

</html>

希望能幫助到你!

不幸的是,現在許多瀏覽器都不支持模塊。

此功能目前才剛剛開始在瀏覽器中原生實現。 它在許多轉譯器(例如 TypeScript 和 Babel)以及打包器(例如 Rollup 和 Webpack)中實現。

MDN 上找到

它對我有用,type="module"添加到腳本import我的 mjs 中:

<script type="module">
import * as module from 'https://rawgit.com/abernier/7ce9df53ac9ec00419634ca3f9e3f772/raw/eec68248454e1343e111f464e666afd722a65fe2/mymod.mjs'

console.log(module.default()) // Prints: Hi from the default export!
</script>

見演示: https : //codepen.io/abernier/pen/wExQaa

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM