As a newcomer to TypeScript, I find myself delving into the depths of this new world. While I grasp the concepts thus far, I am struggling with incorporating external libraries (specifically D3 for manipulating SVG DOM) into my project. In traditional vanilla Javascript, I would simply include the library and my main.js script one after another. However, as my project expands, I aim to utilize TypeScript's advantages in a more modular approach.
The current issue I am facing is a browser error in Chrome:
Uncaught TypeError: Failed to resolve module specifier "d3". Relative references must start with either "/", "./", or "../"
I understand that it points to my import statement, but I cannot seem to find a solution to resolve it.
In my tsconfig.json file, I have the following setup:
{
"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
}
}
An excerpt from my index.html file:
<head>
<script src="../dist/fgn/fgn.js" type="module"></script>
</head>
<body>
<button id="testButton" onClick="unreachableFoo();">Test Script</button>
</body>
Within my ./src/fgn/fgn.ts file:
/* Assuming I want to use the whole library as documented by Mike Bostock.
However, this import statement throws an error in the browser when transpiled
to JavaScript */
import * as d3 from "d3"; // points to '[root]/node_modules/@types/d3' (index.d.ts)
console.log('script is running...');
// This desired functionality aims to access d3 from the global namespace
d3.select('#testButton').on('click', () => {alert('button clicked!');});
// Unfortunately, this also does not work as intended. The browser claims the function is not defined.
function unreachableFoo() { console.log('foo'); }
Despite various attempts with different tsconfig setups and changing the import path to "[root]/node_modules/d3/" (index.js) while enabling "allowJs" in tsconfig, I faced further issues as tsc somehow included the node_modules/@types/ path, resulting in confusion and errors with declaration files there.
Another approach I tried was utilizing webpack, setting up the package.json, and managing dependencies from there. Although I may be on the right track with this method, the browser error persisted.
What could I possibly be overlooking?