If I have a folder, "functions" in the project root directory, with an exported function (in a file, oneFunction.tsx):
export function myFunc() {
const thing = 'Some text';
return thing;
}
and I try to import this in a component like this:
import {myFunc} from '/functions/oneFunction';
It almost works in development, I can use the function, but I get a typescript error:
Cannot find module '/functions/oneFunction' or its corresponding type declarations.
And it won't compile if I run yarn build.
If I remove the slash: {myFunc} from 'functions/oneFunction'; , the typecript error disappears but there is a compilation error:
Failed to resolve import "functions/oneFunction"
So I am wondering how do imports from the root directory?
I have path alias for the "src" folder which works, but I didn't succeed in creating an alias for the root.
I tried this in tsconfig:
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"],
"#root/*": [ "." ]
}
and in vite.config:
resolve: {
alias: {
'@': resolve(__dirname, './src'),
"#root": resolve(__dirname),
},
},
(also installed @types/node and "types": ["node"] to tsconfig)
But it doesn't work: import {myFunc} from '#root/functions/oneFunction';
Update
Here is a reproduction
Update
If I try the same thing on a different project without typescript, I can use the import that starts with a slash with no problem, and it builds ( import {myFunc} from '/functions/oneFunction'; )
Looks like the reason is path in tsconfig: "#root/*": ["./*"]
Here's a solution that works for me for both src and root aliases
tsconfig:
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"],
"#root/*": ["./*"]
}
},
vite.config:
// import { resolve } from 'path';
resolve: {
alias: {
'@': resolve(__dirname, 'src'),
'#root': resolve(__dirname)
}
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With