导入作为 Node 模块安装的 JS 库

Importing a JS library installed as a Node module

我想使用 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

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

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///Users/vahagnhay/Desktop/britecharts-test/chart.js. (Reason: CORS request not http).

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

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

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

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

You need to pay attention to local testing — if you try to load the HTML file locally (i.e. with a file:// URL), you'll run into CORS errors due to JavaScript module security requirements. You need to do your testing through a server.