Javascript导入包无法解析模块说明符

2024-03-14

我正在尝试导入使用 npm 下载的模块。

我的 json 文件是:

{
  "name": "nodejs-web-app1",
  "version": "0.0.0",
  "description": "NodejsWebApp1",
  "main": "server.js",
  "author": {
    "name": ""
  },
  "dependencies": {
    "fs": "^0.0.1-security",
    "http": "^0.0.1-security",
    "node-pandas": "^1.0.5",
    "node-static": "^0.7.11",
    "require": "^2.4.20",
  },
}

我有我的 html 文件:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <title>Home</title>
    <script type="module" src="functions.js"></script>
    <link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
    <h1>Dashboard</h1>
    <p>Welcome!</p>
    <button onclick="scraper()">CLICK</button>
    <label id="label">Reponse</label>
</body>

</html>

我的functions.js 文件

import pd from 'node-pandas';
function scraper() {
    const s = pd.Series([1, 9, 2, 6, 7, -8, 4, -3, 0, 5])
    console.log(s);
    document.getElementById('label').innerHTML = 'A computer science portal for geeks';
}

和我的 server.js 文件:

var nStatic = require('node-static');
var http = require('http');
var fs = require('fs');
var port = process.env.PORT || 8080;

var file = new nStatic.Server(__dirname);

http.createServer(function (req, res) {
    file.serve(req, res);
}).listen(port);

但是运行代码时出现错误

未捕获的类型错误:无法解析模块说明符“node-pandas”。 相对引用必须以“/”、“./”或“../”开头。

我尝试过,但它也给出了另一个错误。

如果我写:

import pd from './node-pandas';

or

import pd from '../node-pandas';

I get:

获取http://localhost:1337/node-pandas net::ERR_ABORTED 404(未找到)

我的项目有这样的结构:

  • myproject
    • 服务器.js
    • 函数.js
    • 索引.html
    • 包.json
    • node_modules
      • 节点熊猫

我正在使用 Visual Studio 2019

知道我做错了什么吗?


我遇到了完全相同的问题(我是一个完全的初学者)。

我通过 NPM 安装了一个依赖项,在该项目中他们使用了 import 语句,例如

import pd from './node-pandas';

代替

import pd from './node-pandas.js';

因此,我遇到了这样一种情况:Live Server 在“http://localhost/scriptname.js”上托管 javascript 文件,而项目则在“http://localhost/scriptname”(没有 .js 扩展名)上查找该文件)

我当然可以将 .js 添加到导入语句中,但随后我必须对此外部项目的所有文件上的所有导入语句执行此操作。

奇怪的是,关于这个错误的信息并不多,但总结一下:

  • 存在模块说明符和相对导入引用之类的东西:https://sbcode.net/thirdjs/module-specifiers/ https://sbcode.net/threejs/module-specifiers/
  • 您只能使用相对导入引用。如果你想使用模块说明符,你需要一个工具来解决这些问题
  • WebPack 就是此类工具的一个示例。它将为您解析所有这些导入语句并生成一个 javascript 文件,您可以将其添加到您的 html 文件中
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Javascript导入包无法解析模块说明符 的相关文章

随机推荐