【问题标题】:'import' statement not working in script in rendered HTML“导入”语句在呈现的 HTML 中的脚本中不起作用
【发布时间】:2019-06-26 01:37:00
【问题描述】:

我正在开发一个快速应用程序,我尝试执行以下操作,但我不断收到相同的错误 - “GET http://localhost:3000/javascript/module2 net::ERR_ABORTED 404 (Not Found)”

有人可以向我指出我犯了什么错误并指出正确的方向吗?下面是我的代码 -

Module1.js

import theFunc from "./module2";
console.log("In module 1");
theFunc();    

Module2.js

export default function theFunc() {
console.log("from module 2");
}

index.html

<html>
 <body>
   Should show the result in console.
  <script type="module" src="./javascript/module1.js"></script>
 </body>
</html>

提前非常感谢! :)

【问题讨论】:

    标签: javascript node.js express ecmascript-6 es6-modules


    【解决方案1】:

    消息指出了问题,但仍然很容易错过。

    GET http://localhost:3000/javascript/module2 net::ERR_ABORTED 404
    

    是问题,因为不是

    http://localhost:3000/javascript/module2
    

    网址实际上是

    http://localhost:3000/javascript/module2.js
    

    带有.js 扩展名。

    问题是

    import theFunc from "./module2";
    

    应该是

    import theFunc from "./module2.js";
    

    【讨论】:

    • 我不得不问,你是对的,但为什么会这样呢?我想如果它是 .js 扩展名,它不需要在 index.js 文件中的导入。
    • 节点可以自动添加.js,因为它可以查看文件系统,如果没有匹配给定名称的文件,它将再次尝试附加.js。从技术上讲,浏览器可能会看到 404,然后在 URL 上附加 .js 重试,但这意味着没有 .js 的每个导入都必须执行两倍的请求,这对性能来说很糟糕。跨度>
    • 在互联网上很难找到这些信息。非常感谢,@loganfsmyth。
    • 谢谢,这对我很有用。
    【解决方案2】:

    import 和export 语句属于ES6,因此你需要使用像Babel 这样的转译器。 你的第二个选择是使用require ES5 中的等价物:

    首先将此脚本添加到您的 html 的头部:

    <html>
    <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js"></script>
    </head>
    <body>
    

    更改这些行:

    import theFunc from "./module2";
    

    变成

     var theFunc = require("./module2");
    

    &这个也是:

    export default function theFunc() {
    console.log("from module 2");
    }
    

    变成:

    function theFunc() {
    console.log("from module 2");
    }
    module.exports = theFunc;
    

    【讨论】:

    • 嗨,Melchia,我尝试了您的解决方案,但我遇到了一个新错误,这又导致了一个新问题 - "Uncaught ReferenceError: require is not defined at module1.js" 有什么建议吗?
    • 我猜你在浏览器中使用了这个。你需要导入require
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    • 2015-08-17
    • 2016-09-26
    • 1970-01-01
    • 2023-03-21
    • 2012-03-15
    相关资源
    最近更新 更多