【问题标题】:Importing a JS library installed as a Node module导入作为 Node 模块安装的 JS 库
【发布时间】:2022-01-22 21:03:17
【问题描述】:

我想使用Britecharts 库设置一个项目。使用npm install --save britecharts d3-selection 安装 Britecharts 后,我正在尝试通过在浏览器中显示基本图表来验证导入是否正常。

我的 index.html:

<!doctype html>
<html class="no-js" lang="">

<head>
  <meta charset="utf-8">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="css/normalize.css">
  <link rel="stylesheet" href="css/style.css">

  <!-- TESTME -->
  <link type="text/css" rel="stylesheet" href="node_modules/britecharts/dist/css/britecharts.min.css">
  <script type="module" src="chart.js"></script>
</head>

<body>

  <div class="bar-container"></div>

</body>

</html>

我的 chart.js:

// For ES modules
import bar from 'britecharts/dist/umd/bar.min';

// Instantiate bar chart and container
const barChart = britecharts.bar();
const container = d3.select('.bar-container');

// Create Dataset with proper shape
const barData = [
    { name: 'Luminous', value: 2 },
    { name: 'Glittering', value: 5 },
    { name: 'Intense', value: 4 },
    { name: 'Radiant', value: 3 }
];

// Configure chart
barChart
    .margin({left: 100})
    .isHorizontal(true)
    .height(400)
    .width(600);

container.datum(barData).call(barChart);

我的文件夹结构:

├── britecharts
│   ├── node_modules
│   ├── package-lock.json
│   └── package.json
├── chart.js
└── index.html

开发控制台给了我这个错误信息:

跨域请求被阻止:同源策略不允许读取位于 file:///Users/vahagnhay/Desktop/britecharts-test/chart.js 的远程资源。 (原因:CORS 请求不是 http)。

我是 JS 项目的新手——我这样做对吗?

【问题讨论】:

  • file:// URL 是可疑的......你是如何运行这个的?您是在打开由本地 Web 服务器提供的本地 URL,还是只是将 HTML 文件从文件系统打开到浏览器中?
  • 是后者,只是将我的HD上的一个文件打开到浏览器中!这就是为什么我没有得到 CORS 的东西。
  • 那就是问题所在。您需要在本地 Web 服务器中运行它,以便您的代码可以发出 AJAX 请求。您可以手动设置服务器,甚至只使用 IDE 中的内置调试服务器。但是仅仅在本地打开一个文件会极大地限制它的功能。
  • @fullstackplus 与你是否使用 AJAX 无关。出于安全原因,这就是主要浏览器(Chrome、Edge、Firefox 等)的工作方式。大多数 IDE 都有可用于简单 Web 服务器的插件。有些甚至默认支持它们。
  • @fullstackplus 但是,我同意 JS 生态系统可能会非常痛苦。无论哪种方式,在简单的 Web 服务器上运行您的应用程序都是您在 2021 年必须做的事情。很多人为此使用的常见方法是:npmjs.com/package/http-server

标签: javascript html cors node-modules directory-structure


【解决方案1】:

加载 JS 模块时,您需要显式使用相对路径。比如./chart.js

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules

[编辑] 此外,您需要在服务器上运行(本地或远程)。同样,请参阅上面的 MDN 模块链接。

您需要注意本地测试——如果您尝试在本地加载 HTML 文件(即使用file:// URL),由于 JavaScript 模块安全要求,您会遇到 CORS 错误。您需要通过服务器进行测试。

【讨论】:

  • 修改了相对路径,没有区别。 Frefox 说Module source URI is not allowed in this document: “file:///Users/vahagnhay/Desktop/britecharts-test/chart.js”.
  • 其实其他cmet都是对的。使用“file://”路径(即在本地加载)将无法加载模块。它必须通过 http(s) 完成。因此,您要么需要在开发机器上启动本地服务器,要么上传到远程服务器进行测试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-12
  • 2021-09-25
  • 2021-08-29
  • 1970-01-01
  • 2018-06-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多