react-server icon indicating copy to clipboard operation
react-server copied to clipboard

Error when using alias in vite.config.js

Open ericdmachado opened this issue 1 year ago • 3 comments

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

ericdmachado avatar Sep 14 '24 15:09 ericdmachado

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,
    },
  },
});

lazarv avatar Sep 15 '24 17:09 lazarv

@ericdmachado curious is the fix working for you? thanks

mrose avatar Nov 14 '24 16:11 mrose

@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.

lazarv avatar Nov 14 '24 20:11 lazarv