我知道这可能是个很傻的问题。但是,对我来说,最终真正掌握它将是非常重要的!
因此,我只想在浏览器中包含和使用D3 (但可以是任何其他npm包)。
所以我创建了一个目录和一个index.html。我用npm init -y启动了一个新的npm项目,我安装了npm install d3.我创建了一个名为main.js的文件,如下所示:
// main.js
import * as d3 from "d3";
console.log(d3.scaleLinear());在哪里index.html
// index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./main.js" defer></script>
</head>
<body>
this is the body
</body>
</html>看起来像这样,package.json是这样的:
{
"name": "HowDoesNpmWork",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"d3": "^7.6.1"
}然而,在运行npx serve之后,我确实在浏览器中得到了错误。
Uncaught SyntaxError: import declarations may only appear at top level of a module main.js:1我可不想把它搞清楚。我正在安装D3,我说它是package.json中的一个模块。我在这里从概念上误解了什么?我不能简单地使用任何npm包在前面吗?
当我在D3中像这样导入index.html时,它为什么会工作呢?
import * as d3 from "https://cdn.skypack.dev/d3@7";它不是和从node_modules加载它一样吗?
我会
发布于 2022-09-16 21:08:40
您必须添加代码是一个模块。
<script src="./main.js" type="module"></script>这仍然取决于允许这样的直接导入的D3。并不是所有用npm install安装的软件包都能像这样直接在浏览器中工作。
另一种解决方案是使用像parcelJS这样的模块绑定器。这是在前端使用npm的更为传统的方法。
https://stackoverflow.com/questions/73750198
复制相似问题