vercel / edge-runtime

Developing, testing, and defining the runtime Web APIs for Edge infrastructure.
https://edge-runtime.vercel.app
MIT License
830 stars 79 forks source link

Absolute import paths in Vercel production. #972

Open mrrobot16 opened 2 months ago

mrrobot16 commented 2 months ago

Hello people of Vercel community!

Hope you all doing great :)

I am creating this issue to ask if it is actually possible to do absolute imports in production mode.

I was able to do it in: vercel dev.

My project structure:

├── .vercel/ ├── api/ │ ├── health/ │ │ ├── [step].ts │ │ ├── health.ts │ │ └── test.ts ├── dist/ ├── lib/ │ ├── utils/ │ │ └── index.ts │ ├── utils-v2/ │ │ └── index.ts ├── node_modules/ ├── public/ │ └── .gitignore ├── .gitignore ├── middleware.ts ├── package.json ├── README.md ├── tsconfig.json ├── vercel.json ├── yarn.lock

Key directories and files:

My tsconfig.json:

{
    "compilerOptions": {
        "target": "esnext",
        "module": "esnext",
        "moduleResolution": "node",
        "outDir": "./dist",
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true,
        "strict": true,
        "skipLibCheck": true,
        "lib": [
            "ESNext",
            "ESNext.AsyncIterable",
            "dom",
            "es2020"
        ],
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": true,
        "jsx": "preserve",
        "incremental": true,
        "baseUrl": "./lib", // This enables absolute imports from 'src'
        "paths": {
            "@/lib/*": [
                "*"
            ] // Allows '@' to map to anything in 'src'
        }
    },
    "include": [
        "lib/**/*", // Include everything inside 'src'
        "api/**/*" // Include the API files in root
    ],
    "exclude": [
        "node_modules",
        "**/*.test.ts"
    ]
}

My code

import axios from 'axios';

import { createGreeting } from '@/lib/utils';
import { createGreetingV2 } from '@/lib/utils-v2';

export const config = {
  runtime: 'edge',
};

export default async function handler(req: Request) {
    const url = new URL(req.url)
    const baseUrl = `${url.protocol}//${url.host}`;
    const test = (await axios.get(`${baseUrl}/api/test`))

    const data = {
        message: 'Hello world!',
        greeting: createGreeting('Hector'),
        greetingV2: createGreetingV2('John'),
        test: test.data,
    };

    const headers = {
    'Content-Type': 'application/json',
    };

    return new Response(JSON.stringify(data), { headers });}

my vercel.json

{
    "functions": {
      "api/**/*.ts": {
        "memory": 3009,
        "maxDuration": 30
      }
    }
  }

My error:

Error: The Edge Function "api/health/[step]" is referencing unsupported modules:
    - __vc__ns__/0/api/health/[step].js: @/lib/utils, @/lib/utils-v2

My repo: https://github.com/mrrobot16/edge-api-route