deno relative path issue
Asked Answered
B

1

8

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"

Baiss answered 10/2, 2022 at 20:7 Comment(0)
C
9

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/[email protected]/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
Comma answered 10/2, 2022 at 23:49 Comment(2)
I'm still unable to make that work, when defining a bare specifier for some relative folder, like asked in the question. The example given in the answer explains only the case with a remote dependency. Would be great to have some example also for local relative deps and a bare specifier alias.Kristalkristan
^ @Kristalkristan Sure — I updated the answer with a demonstration of that in the form of console i/o.Comma

© 2022 - 2024 — McMap. All rights reserved.