sachaw
sachaw•5mo ago

Importing deno modules with import maps

Hi, I am currently trying to import a deno library either locally or via url. The library contains a deno.json file containing an import map for jar packages. I have tried importing the mod.ts file (which thows an error complaining about local imports (no import map to resolve them). Also tried importing the deno.json but you can't import json modules like this AFAIK. Any ideas? Thanks.
3 Replies
Deno AI Helper
Deno AI Helper•5mo ago
Hello! Import maps in Deno are a powerful feature that allows you to control how import specifiers are resolved. To use an import map in your Deno project, you should follow these steps: 1. Create an import_map.json file in your project where you will define your import aliases and their corresponding paths. 2. In your deno.json or deno.jsonc configuration file, add an importMap field with the path to your import map file. For example:
{
"importMap": "./import_map.json"
}

{
"importMap": "./import_map.json"
}

3. Define your import map by specifying the aliases and the corresponding paths in the import_map.json file. Here's an example of what it might look like:
{
"imports": {
"mylib/": "./path/to/mylib/",
"jar/": "./path/to/jar_packages/"
}
}

{
"imports": {
"mylib/": "./path/to/mylib/",
"jar/": "./path/to/jar_packages/"
}
}

4. Now, you can use these aliases in your imports. For instance, if you want to import mod.ts from your library, you can do so like this:
import { myFunction } from "mylib/mod.ts";

import { myFunction } from "mylib/mod.ts";

5. When running your Deno commands, make sure to include the --import-map flag followed by the path to your import map file. For example:
deno run --import-map=./import_map.json main.ts

deno run --import-map=./import_map.json main.ts

The documentation also mentions that the deno.json file is auto-discovered and acts, among other things, as an import map. This means that once you have your deno.json and import map file set up, Deno will automatically use the import map when resolving module imports. Remember that import maps are intended for use in applications, not libraries. If you are developing a library, you should use the deps.ts pattern to manage dependencies instead. If you're still encountering errors after setting up your import map, please ensure that the paths specified in the import
Deno AI Helper
Deno AI Helper•5mo ago
map are correct and that the --import-map flag is being used when running your Deno commands. If the issue persists, you might want to share the specific error message you're getting so that we can provide more targeted assistance. 🦕
benjamn
benjamn•5mo ago
https://docs.deno.com/runtime/manual/basics/import_maps/#import-maps-are-for-applications You would have to copy it to your own deno.json, modifying imports as needed. Or you can run it inside of the module. Adding entries to it for local imports...