1

I have this problematic import.

import * as Collection from '../../lib/collection.js'

root
> lib
>> collection.js
> tests
>> folder1
>>> collection.spec.js

how can resolve this relative path with something like

import * as Collection from '@/lib/collection.js' 
OR
import * as Collection from 'lib/collection.js'

tried both. neither worked.

any ideas?

Tadas V.
  • 775
  • 1
  • 11
  • 22

1 Answers1

1

I’m not sure what you mean when you say “problematic”, as that import looks correct/like it should work fine. Is it not working for you?

If your concern is that you’d rather avoid having to go up directories with ../ leading to the two options you tried, and you’re trying to get something like that to work, that’s addressed better than I could elsewhere such as this accepted answer about what @ does and the others. Short answers:

  1. lib/collection.js isn’t relative, and would refer to a package (see also Node’s doc on import specifiers
  2. @/lib/collection.js isn’t a natively supported JavaScript syntax and requires a module loader/bundler, but should work once set up.
David R
  • 493
  • 2
  • 8
  • thx for response. but I still need to find a way to resolve relative paths to root... – Tadas V. Jul 22 '23 at 17:44
  • Did those links not help? It’s definitely not native JavaScript or Node to be able to do that. Are you using TypeScript or some other tool that could be used to add that functionality? I may be able to give a more specific answer for a config or something depending on what tool you’re using – David R Jul 22 '23 at 21:39
  • no really. but it narrowed it all down. I was fixated on wrong approach. In the end solved with node process.cwd() – Tadas V. Jul 22 '23 at 22:13
  • Oh interesting, I didn’t realize you could use something like that in imports Could you share the solution you ended up coming to? – David R Jul 23 '23 at 02:25
  • sorry for confusion. it was NOT process.cwd in import. i used it in file dir. there were a lot of changes in that project architecture:)) as for op i think i just bit the bullet and did relative paths like '../..' – Tadas V. Jul 23 '23 at 02:51
  • Ah okay, no worries, and sounds good! – David R Jul 23 '23 at 07:57