4

At runtime, for the browser, I need

import * as d3 from '../lib/d3.js';

to correctly fetch d3. I verified that this does work indeed. But the file containing the above, call it main.js, is generated from a typescript file main.ts which currently starts with the very same line above.

The typescript compiler complains that it cannot find the module or its declarations. I thought to fix this with something along the lines of

  "paths": {
     "../lib/d3.js": ["node_modules/@types/d3"]
  },

but from the Typescript handbook I cannot see how to write this correctly: shall the key be the full file path or just a module name? What about the value array: file paths, directories?

Can this be done with path mapping in tsconfig.json at all? (I know how to get this going with webpack, but I am now interested to know how to do without.)

Related: https://github.com/microsoft/TypeScript/issues/37971, but does not help me.

Harald
  • 4,575
  • 5
  • 33
  • 72

1 Answers1

3

According to the following reasoning, what the OP wants cannot be done as of March 2022:

  1. In the browser, imports of modules must be a relative or absolute path: "In some module systems, you can omit the file extension and the leading /, ./, or ../ (e.g. 'modules/square'). This doesn't work in native JavaScript modules."
  2. According to a comment on a very old Typescript issue, the compiler does not rewrite import paths, ever.
  3. The Typescript handbook says: "A relative import is resolved relative to the importing file and cannot resolve to an ambient module declaration.

So the first two require to write the exact relative path import statement into the .ts file that will be understood by the browser, while the third statement says that we cannot re-map these relative paths for the compiler to find declarations.

Bottom line: there is no way without a bundler as soon as we (a) use a Javascript library with a .d.ts and (b) target a browser.

Late addition (2022-09): Webpack has its own issues with .js imports for Typescript that need to be solved with yet another plugin, see this answer.

Harald
  • 4,575
  • 5
  • 33
  • 72
  • Can't help to wonder whether (3) is cast in stone. Asking the compiler to map a relative path like `./lib/d3.js` to some `.../d3/index.d.ts` does not seem that far out. There is for sure an issue already ... (off to find it). – Harald Mar 20 '22 at 07:35