import报错Uncaught SyntaxError: Cannot use import statement outside a module

前端这点事 27 0

看到import模块化的时候,本想着自己也试试常用的几种模块引入方式和导出方式,打开vscode,新建index.html和module.js,跑起live-server.

正当我准备看效果的时候,控制台报错了。

简单贴下代码:

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>es6 import</title>
</head>

<body>
    <script>
        import * as module from './module.js'
        module.alert('hello xinxin')
    </script>
</body>

</html>

module.js

const alert = (msg) => {
    window.alert(msg)
}

export { alert }

我去,这是一个什么神仙错误,google一下,发现当在html、js引入的时候,需要加上type="module",额,好吧,就是这么简单,简单记录下:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>es6 import</title>
</head>

<body>
    <script type="module">
        import * as module from './module.js'
        module.alert('hello xinxin')
    </script>
</body>

</html>

标签: JavaScript

发表评论 (已有0条评论)

还木有评论哦,快来抢沙发吧~