I have the following file:
import {something} from '../../something';
something.do();
And I want to get something's relative path as a string, but dynamically rather than to write it implicitly. Something like this:
import {something} from '../../something';
getPath(something); // will return '../../something'
something.do();
What are my options? Is it even possible?
You can get a relative path to an imported file as follows
FIRST APPROACH: (the imported file is modified):
test folder. Inside the test folder, you have test1.js and /mod/test2.js files.test/mod/test2.js
// here are some of your codes
export const importedFilePath = import.meta.url; // export current file absoulte path
test/test1.js file:path.relative(from, to) method returns the relative path from to to based on the current working directory. If from and to each resolve to the same path (after calling path.resolve() on each), a zero-length string is returned.
If a zero-length string is passed as from or to, the current working directory will be used instead of the zero-length strings. Documentation
import path from 'path'
import { importedFilePath } from './mod/test2.js';
const currentFilePath = import.meta.url;
console.log(path.relative(currentFilePath, importedFilePath));
Output:
..\mod\test2.js
Now you have the relative path from test/test1.js to test/mod/test2.js
I know this is not a perfect solution but you can achieve the result you want using the above approach.
SECOND APPROACH
If you would be using the CommonJS module system you can be achieved this result without modifying the imported file.
Assume you use the CommonJS module. Without any modification to the imported file you can achieve the same result as above as follows:
test/test1.js file:
const file = require('./mod/test2');
const path = require('path');
const importedFilePath=require.cache[__filename].children[0].id; //this returns imported file path
const currentFilePath = __filename;
console.log(path.relative(currentFilePath, importedFilePath));
And output:
..\mod\test2.js