【发布时间】:2021-05-30 20:02:54
【问题描述】:
我是 TypeScript 的新手,只是在钻研那个兔子洞。我想,到目前为止我理解了这个概念,但我不明白的是我最终是如何使用库的(在我的例子中,D3 用于操作 SVG DOM)。在 vanilla Javascript 中,我只是通过一个又一个地包含库和我的 main.js 脚本来以老式方式完成它,但是随着我的项目的增长,我想通过模块化方法来使用 TypeScript 的优势。
当前问题是这个浏览器错误(Chrome):
未捕获的类型错误:无法解析模块说明符“d3”。相对引用必须以“/”、“./”或“../”开头
嗯,我知道它指向我的导入语句,但我不知道如何解决它。
tsconfig.json
{
"compilerOptions": {
"target": "ES5",'ESNEXT'. */
"module": "ESNext",
"declaration": true,
"outDir": "./dist/fgn/",
"rootDir": "./src/fgn/",
"strict": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"skipLibCheck": true, // required to avoid checking d3 type definitions
"forceConsistentCasingInFileNames": true
}
// ,"files": [],
// "include": [],
// "exclude": []
}
index.html(摘录)
<head>
<script src="../dist/fgn/fgn.js" type="module"></script>
</head>
<body>
<button id="testButton" onClick="unreachableFoo();">Test Script</button>
</body>
./src/fgn/fgn.ts
/* Assuming I want to use the whole library. That's how it is documented by Mike Bostock.
However, this import statement throws an error in the browser (tested in Chrome, Firefox)
when being transpiled to javascript */
import * as d3 from "d3"; // points to '[root]/node_modules/@types/d3' (index.d.ts)
console.log('script is running...');
// This is the desired functionality I want to gain: having access to d3 from global namespace (globalThis ?)
d3.select('#testButton').on('click', () => {alert('button clicked!');});
// Also this is not working. The browser complains the function is not defined.
function unreachableFoo() { console.log('foo'); }
我尝试了多个 tsconfig 设置并将导入更改为指向“[root]/node_modules/d3/”(index.js),同时在 tsconfig 中启用“allowJs”,但这导致了进一步的问题,因为 tsc 以某种方式包含了node_modules/@types/ 路径导致声明文件混乱和错误。
另一个尝试是使用 webpack,设置 package.json 并从那里构建依赖项。也许我在正确的轨道上,但浏览器错误仍然存在。
我错过了什么?
【问题讨论】:
-
顺便说一句,
import语句不是 TypeScript 独有的,实际上在纯 JS 中也是如此。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
标签: javascript typescript tsconfig tsc