lazarv / react-server

The easiest way to build React apps with server-side rendering
https://react-server.dev
MIT License
121 stars 6 forks source link

Error when using alias in vite.config.js #39

Open ericdmachado opened 2 months ago

ericdmachado commented 2 months ago

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

lazarv commented 2 months ago

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,
    },
  },
});
mrose commented 1 week ago

@ericdmachado curious is the fix working for you? thanks

lazarv commented 1 week ago

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