Thanks to @Alex Craft answer: https://stackoverflow.com/a/78658715/3266845 please vote him up instead.
I noticed:
UserConfig
object worked! But it felt silly defining it in two places.So I tried:
vite-tsconfig-paths
but it did not work all the way, the resolved values would turn null
later on even though the same path was successfully resolved earlier. I could not find a reason for this, but you can check how yours resolves by running DEBUG=vite:resolve npm run YourStartScript
. Tried using loose
option and it didn't work. allowJs
is enabled in tsconfig.tsconfig.json + package.json
strategy and not defining in vite.config.ts
did not work for me.It could very well be me missing something, but I spent some hours trying different things and observing how imports resolve but could not make sense of it. I think the issue is occurring somewhere between my (a) monorepo setup (b) root tsconfig and package tsconfig extends (c) rootDir baseUrl incorrectly set up? (d) storybook-vite (?)
I think @Alex Craft is the most reasonable answer and it almost worked for me. I had to make some changes, shown below.
import { parse } from 'jsonc-parser';
export default defineConfig({
...
resolve: {
alias: getPathsFromTsConfig()
},
...
});
function getPathsFromTsConfig() {
const tsconfig = parse(fs.readFileSync('./tsconfig.json', 'utf-8'));
const aliases = {};
for (const [key, value] of Object.entries(tsconfig.compilerOptions.paths)) {
const cleanKey = key.replace('/*', '');
const cleanValue = value[0].replace('/*', '');
const resolvedPath = path.resolve(__dirname, cleanValue);
aliases[cleanKey] = resolvedPath;
}
return aliases;
}