Is there a way to handle subpath imports within a library?
I'm trying to convert a library package to work with deno.
Internally, the package makes a bunch of (different) subpath imports from another library of ours.
If this were an application making these imports, I'd just use an import map. However, the docs are pretty clear that, for a library, you should create a
deps.ts
. The problem with this is that I have to enumerate every single subpath import in the deps
file to make it available to other files.
Is there a pattern for import map style mappings, for a library?2 Replies
The documentation suggests that traditionally, Deno has handled dependencies within a library by using a
deps.ts
file, which re-exports all remote dependencies. This file serves as a single source of truth for managing and organizing dependencies, making it easier to update package versions since all external dependency specifiers live in the same file.
However, the documentation also acknowledges that deps.ts
is not particularly ergonomic, as it necessitates flattening and re-exporting every symbol one depends on. This can be more verbose and syntactically cluttered compared to other methods like package.json
with bare specifiers.
To address the issue of handling subpath imports within a library, the documentation mentions that Deno has introduced improvements to the imports
field in deno.json
. This enhancement allows you to specify dependencies with subpath exports more simply. For example, you can now use a single entry in the imports
field to cover both the main import and its subpaths, which would be expanded into two entries in an internal import map used for resolution.
Here's an example from the documentation showing the simplified syntax:
In Deno 1.40.0 and later, this configuration allows you to import both preact
and preact/hooks
from npm without having to enumerate every subpath.
While this feature is primarily designed for applications, it could potentially be used in a library context as well, provided that the library's users are willing to include the library's import map in their own project's configuration. However, the documentation also notes that import maps are not composable, which means that a library cannot use bare specifiers and an import mapsimultaneously, as the top-level project importing that library cannot compose the library’s import map with its own.
Given these constraints, if you are looking to convert a library package to work with Deno and it makes extensive use of subpath imports, you might need to consider a hybrid approach. You could use a
deps.ts
file for the main imports and provide additional guidance on how to handle subpath imports using the improved imports
field in deno.json
, with the understanding that users of your library will need to integrate this into their own import maps.
🦕 If you have further questions or need more specific guidance, feel free to ask!