【问题标题】:I can't fixed a problem of "Uncaught SyntaxError: Cannot use import statement outside a module" [duplicate]我无法解决“未捕获的语法错误:无法在模块外使用导入语句”的问题 [重复]
【发布时间】:2020-01-31 23:58:30
【问题描述】:

我在一个文件夹中有“三个”文件 1. 索引.html 2. 索引.js 3. helper.js

我想从helper.js 导出代码并将代码导入index.js(我已经将index.js 链接到index.html)。

我确实喜欢 index.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>Document</title>
</head>
<body>

    <button id="btn">click</button>


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

index.js

import btn from './helper'

btn.addEventListener('click', function () {
    window.alert('i am clicked')
})

最后是 helper.js

export let btn = document.getElementById('btn')

然后我在 chrome 浏览器中运行 index.html 文件。

Chrome 浏览器在控制台中显示此消息。

未捕获的语法错误:无法在模块外使用 import 语句

请告诉我如何解决这个问题。我在 google 和 youtube 上搜索,我做了他们展示的同样的事情。结果,浏览器显示该消息。

【问题讨论】:

    标签: javascript ecmascript-6


    【解决方案1】:

    您需要在某个端口(例如 5500)上通过网络服务器提供您的文件。然后将您的浏览器指向该端口,即 localhost:5500/

    这将是浏览器从另一个 js 文件导入其他模块的唯一方法。

    见...MDN Doc on Modules

    • 您可以使用 npm 包 http-server。
    • 如果您使用的是 Visual Studio Code,则可以使用扩展 Live Server。
    • 或者您喜欢的任何其他服务器都可以在您的系统上运行。

    接下来,您需要将 type="module" 添加到您的脚本标签中。

    <button id="btn">click</button>
    
    
    <script type="module" src="./index.js"></script>
    

    你的 index.js 试试这个......

    import { btn } from './helper.js'
    

    最后是你的 helper.js ....

    const btn = document.getElementById('btn');
    
    export { btn };
    

    您可能还考虑在作为模块的 js 文件上使用 .mjs 扩展名。让大家知道它确实是一个模块。

    【讨论】:

    • 我终于解决了我的问题..我的问题在 .babelrc 文件中...好的谢谢
    • 好 :) .babelrc 文件中的问题是什么?它可能会帮助其他人在底部使用您的解决方案来编辑​​您的原始问题。编码愉快!
    【解决方案2】:

    您需要在模块中包含您的导入:

    试试这个:

    <script type="module">
       import btn from './helper'
    </script>
    

    参考:ES Modules in Browsers

    【讨论】:

    • 我试过 type="module" 但它显示错误 Access to script at 'file:///D:/testing/index.js' from origin “null”已被 CORS 策略阻止:跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https。
    • 现在又出现了一个错误。您试图访问没有来源的脚本。 chrome 之类的浏览器不允许您使用 JavaScript 访问本地文件系统上的文件。你需要安装一个像 LiveServer 这样的网络服务器。
    • 我不会那样做的
    • 你的答案令人困惑
    猜你喜欢
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    相关资源
    最近更新 更多