(Vite) Absolute Path, Absolute Imports, Custom Path, Resolve Alias
Introduction
Let me explain this using an example.
vite.config.ts
If it is not set, it doesn't work.
// If '@types/node' is installed, red lines in '__dirname' and 'path' will be removed.
// However, it works even if it isn't installed.
import { defineConfig } from 'vite';
import * as path from 'path';
// https://vitejs.dev/config/
export default defineConfig({
resolve: {
alias: {
// An empty string doesn't work.
// '': path.resolve(__dirname),
// '/' works.
'/': path.resolve(__dirname),
// It seems to me adding '@' is the custom.
'@src': path.resolve(__dirname, 'src'),
},
},
});
tsconfig.json
If it isn't set, red lines in paths will be shown. But it works.
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"/*": ["./*"],
"@src/*": ["./src/*"]
}
}
}
Folder Structure
src
|-absolutepath
|-App.tsx
|-Child1.tsx
|-Child2.tsx
App.tsx
import Child1 from '/src/absolutepath/Child1';
import Child2 from '@src/absolutepath/Child2';
export default function App() {
return (
<div>
<Child1 />
<Child2 />
</div>
);
}