Error when using alias in vite.config.js
Describe the bug
I am using aliases to make it easier to import modules and components into my project, however, there seems to be a problem when searching for the directory that causes it to get lost during the import. Ex.:
{ resolve: { alias: { '@assets': path.resolve(__dirname, 'src/assets/'), '@styles': path.resolve(__dirname, 'src/styles/'), '@components': path.resolve(__dirname, 'src/components/'), } } }
Reproduction
https://github.com/ericdmachado/react-server-test
Steps to reproduce
No response
System Info
Node 21.7.3 e npm 10.8.3
Used Package Manager
pnpm
Logs
No response
Validations
- [X] Follow our Code of Conduct
- [X] Read the Contributing Guidelines.
- [X] Read the docs.
- [X] Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
- [X] Check that this is a concrete bug. For Q&A open a GitHub Discussion.
- [X] The provided reproduction is a minimal reproducible example of the bug.
Thanks for reporting @ericdmachado! resolve.alias objects are now supported, please upgrade the framework to the latest version.
Keep in mind, that you still need to use Vite configuration in ESM or CommonJS formats, but don't mix these.
When using CommonJS to support __dirname usage, you need to use module.exports in vite.config.js:
// vite.config.js
const { join } = require("path");
module.exports = {
resolve: {
alias: {
"@/": join(__dirname, "src/"),
},
},
};
When using the ESM format, you can use export default, but you can't use __dirname. You need to name your configuration file vite.config.mjs and you need to construct your path alias using new URL and import.meta.url:
// vite.config.mjs
import { defineConfig } from "vite";
export default defineConfig({
resolve: {
alias: {
"@/": new URL("src/", import.meta.url).pathname,
},
},
});
@ericdmachado curious is the fix working for you? thanks
@mrose is it working for you? The Photos example uses this at https://github.com/lazarv/react-server/blob/main/examples/photos/vite.config.mjs. But let me know if there's still an issue in this topic that needs my attention.