How to Use Import Map in Deno for Module Aliasing
In Deno, use an
import_map.json file to define aliases for module paths and run your script with deno run --import-map=import_map.json. This lets you import modules using simple names instead of full URLs or paths.Syntax
An import map in Deno is a JSON file that maps module specifiers to URLs or local paths. It has a imports object where keys are the aliases you want to use in your code, and values are the actual module locations.
To use it, run your Deno script with the --import-map flag followed by the path to your import map file.
json
{
"imports": {
"alias/": "https://example.com/modules/"
}
}Example
This example shows how to create an import map to alias a URL and then import a module using that alias in your Deno script.
typescript
// import_map.json { "imports": { "lodash/": "https://cdn.skypack.dev/lodash-es/" } } // main.ts import { chunk } from "lodash/chunk"; console.log(chunk([1, 2, 3, 4], 2));
Output
[[1,2],[3,4]]
Common Pitfalls
- Forgetting to use the
--import-mapflag when running your Deno script will cause imports using aliases to fail. - Aliases must end with a slash
/if you want to map a folder; otherwise, Deno treats it as a file. - Import map JSON must be valid and properly formatted; syntax errors will cause Deno to reject it.
bash
// Wrong usage (missing --import-map flag) denorun main.ts // Correct usage // deno run --import-map=import_map.json main.ts
Quick Reference
| Feature | Description |
|---|---|
| import_map.json | JSON file defining module aliases |
| --import-map | Deno CLI flag to specify the import map file |
| Alias ending with / | Indicates a folder alias for multiple modules |
| Alias without / | Indicates a single file alias |
| Valid JSON | Import map must be valid JSON or Deno will error |
Key Takeaways
Use an import map JSON file to create simple aliases for module imports in Deno.
Always run your script with the --import-map flag to enable the import map.
End aliases with a slash to map folders, or omit it for single files.
Ensure your import map JSON is valid and well formatted.
Import maps help keep your code clean by avoiding long URLs or relative paths.