【发布时间】:2019-02-10 23:57:51
【问题描述】:
我刚开始进行 Web 开发,但在将使用 npm i MODULE -S 安装的模块导入到 .html 中的 script 时遇到问题。我的文件结构类似于:
设置:
project
|_ node_modules
|_ public
| |_ css
| |_ js
| | |_ libs
| | |_ index.mjs
| |_ index.html
|_ server
|_ server.mjs
index.html 文件非常简单,类似于:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/styles.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>JSON and AJAX</title>
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> -->
</head>
<body>
<header>
<h1>JSON and AJAX</h1>
<button id="btn">Fetch Info for 3 New Objects</button>
</header>
<div id="animal-info"></div>
<script type="module" src="js/index.mjs"></script>
<div id="msgid"></div>
</body>
</html>
还有index.mjs 文件:
import $ from 'jquery';
为了完整起见,server.mjs 文件
// const path = require('path');
import path from 'path';
import express from 'express';
const app = express();
const __dirname = path.resolve();
const publicPath = path.join(__dirname, '/public');
app.use(express.static(publicPath));
const port = process.env.PORT || 8080;
app.set('port', port);
app.listen(app.get('port'), () => {
console.log(`listening on port ${port}`);
});
问题
当我运行 node --experimental-modules server/server.mjs 时,我的页面加载并且我能够在 localhost:8080 中访问它,但是当我在 chrome 中打开开发人员工具时,我遇到了以下错误:
Uncaught TypeError: Failed to resolve module specifier "jquery". Relative references must start with either "/", "./", or "../".
尝试的解决方法
1) 我已将 index.mjs 文件中的 import 语句更改为:
import $ from '.jquery';
import $ from './jquery';
'import $ from '../../node_modules/jquery';
输出以下消息:
GET http://localhost:49160/js/jquery net::ERR_ABORTED 404 (Not Found)
GET http://localhost:49160/js/jquery net::ERR_ABORTED 404 (Not Found)
GET http://localhost:49160/node_modules/jquery net::ERR_ABORTED 404 (Not Found)
2) 我尝试将jquery 文件夹从node_modules 目录复制到libs 目录并重新运行,以便index.js 仅具有以下代码:
import $ from './libs/jquery';
但我收到以下错误:
GET http://localhost:49160/js/libs/jquery/ net::ERR_ABORTED 404 (Not Found)
额外
当我按照Mozilla developer 页面上的文档开发自己的模块时,一切正常,但是当我尝试使用第三方模块时,我遇到了一系列错误。
【问题讨论】:
-
HTTP 404 与模块无关 - 您的文件在您尝试加载的路径中不可用。
-
看到您对 Web 开发非常陌生,为什么还要浪费时间学习像 jQuery 这样的遗留库?您应该花时间学习现代 Web 开发框架,例如 Angular、React 或 Vue。不要浪费时间学习这种过时的方法。
-
@Adran Brand,目标是学习 React。我刚刚选择了
jQuery作为示例模块,认为它会使上述解释更容易,但我无法导入我使用npm install安装的任何其他第三方模块。
标签: javascript node.js es6-modules