Search code examples
typescriptdeno

deno relative path issue


I wanted to some prefixes for my imports like you can see in the code below:

"paths": {
          "~/*": ["../../libs/*"],
          "@/*": ["./*"]
        }

however I always get an relative import path "@/config.ts" not prefixed with / or ./ or ../ts(10001) when I try to import anything import User from "@/config.ts"


Solution

  • You can alias import specifiers by using an import map. From the Deno manual:

    You can use import maps with the --import-map=<FILE> CLI flag.

    Example:

    import_map.json

    {
       "imports": {
          "fmt/": "https://deno.land/std@0.125.0/fmt/"
       }
    }
    

    color.ts

    import { red } from "fmt/colors.ts";
    
    console.log(red("hello world"));
    

    Then:

    $ deno run --import-map=import_map.json color.ts
    

    Update: Here's an demonstration of importing a local module using an import map specifier (as requested in a comment by Kamafeather):

    % ls -AF
    import_map.json     main.ts         path/
    
    % cat import_map.json
    {
      "imports": {
        "local/": "./path/to/local/modules/"
      }
    }
    
    % cat main.ts
    import { shout } from "local/example.ts";
    
    shout("hello world");
    
    % ls -AF path/to/local/modules
    example.ts
    
    % cat path/to/local/modules/example.ts
    export function shout(text: string): void {
      console.log(text.toUpperCase());
    }
    
    % deno --version
    deno 1.34.3 (release, aarch64-apple-darwin)
    v8 11.5.150.2
    typescript 5.0.4
    
    % deno run --import-map=import_map.json main.ts
    HELLO WORLD