0

I have this import that works

import { dirname, default as path } from 'path';

but I don't understand why it needs to be declared this way, instead of

import { dirname, path } from 'path';
import { dirname, * as path } from 'path';

I had a look at examples in Can you import node's path module using import path from 'path' and none suggested the variant above that actually works.

Can someone please explain why it needs to be imported specifically with 'default' and also if this is the best way to import these two modules together.

user2066480
  • 1,229
  • 2
  • 12
  • 24
  • 3
    I'd use `import path, { dirname } from 'path';`, which is shorter and clearer. –  Apr 19 '22 at 22:04
  • Why can't path go together with dirname, inside { } ? I don't understand the syntax... – user2066480 Apr 19 '22 at 22:09
  • "*import these two modules together.*" - I see only one module? – Bergi Apr 19 '22 at 22:20
  • Because `path` is the default export. You can either do `path.dirname`, or straight up destructure `dirname` by doing `{ dirname }` – mstephen19 Apr 19 '22 at 22:21
  • @user2066480 It *can* go together with `dirname as dirname` inside the braces, that's what the first snippet in your question is doing? Not sure what you're looking for. – Bergi Apr 19 '22 at 22:21
  • 1
    @mstephen19 Importing is aliasing, not destructuring. – Bergi Apr 19 '22 at 22:22
  • @user2066480 How do you intend to use `path` and `dirname`? – Bergi Apr 19 '22 at 22:22
  • Did you read https://nodejs.org/api/esm.html#builtin-modules? – Bergi Apr 19 '22 at 22:24
  • @Bergi thanks for the technical term I was looking for! haha – mstephen19 Apr 19 '22 at 22:24
  • 1
    "*it needs to be imported specifically with 'default'*" - no it doesn't. `import { dirname, path } from 'path';` is doing something very different though. You're supposed to use `import * as path from 'path';`, as suggested in the question that you linked. – Bergi Apr 19 '22 at 22:24
  • I read https://nodejs.org/api/esm.html#import-statements, I didn't read https://nodejs.org/api/esm.html#builtin-modules. I guess I was calling 'modules' to functions? – user2066480 Apr 19 '22 at 22:58
  • So the function path is the default for the module path, is that it? I still don't understand why it works outside the { } but not inside... – user2066480 Apr 19 '22 at 23:00
  • I have a module file containing all the database functions and I need the file to be aware of its location, so it can find the database file in another directory (go back one level, enter another dir). I started this sometime ago, I think a relative path string didn't work (../db/file), I had to switch to a path.join() function to get it working, thus the imports. – user2066480 Apr 19 '22 at 23:08
  • In that case, use `* as path` and `path.join()`, or `{ join }` and `join()`. – Bergi Apr 19 '22 at 23:16

0 Answers0