medusajs / medusa

The world's most flexible commerce platform.
https://medusajs.com
MIT License
26.2k stars 2.66k forks source link

Astro & Vite: Cannot use import statement outside a module #9814

Open yannickschuchmann opened 1 month ago

yannickschuchmann commented 1 month ago

Bug report

Code(from v2 docs):

import Medusa from "@medusajs/js-sdk";

// Defaults to standard port for Medusa server
let MEDUSA_BACKEND_URL = "http://localhost:9000";

if (import.meta.env.PUBLIC_MEDUSA_BACKEND_URL) {
  MEDUSA_BACKEND_URL = import.meta.env.PUBLIC_MEDUSA_BACKEND_URL;
}

export const sdk = new Medusa({
  baseUrl: MEDUSA_BACKEND_URL,
  debug: import.meta.env.NODE_ENV === "development",
  publishableKey: import.meta.env.PUBLIC_MEDUSA_PUBLISHABLE_KEY,
});

Error:

/.../frontend/node_modules/.pnpm/@medusajs+js-sdk@2.0.1_awilix@8.0.1_vite@5.4.7/node_modules/@medusajs/js-sdk/dist/esm/index.js:1
import { Admin } from "./admin";
^^^^^^

SyntaxError: Cannot use import statement outside a module

Describe the bug

I try to use @medusajs/js-sdk with astro. But just when I import Medusa vite complains about the import. I was reading similar issues which got closed because things should be different with V2. Any ideas?

System information

Medusa version (including plugins): 2.0.1 Node.js version: v20.16.0 Database: Postgres Operating system: MacOS Sonoma 14.6.1 Browser (if relevant): Arc

Steps to reproduce the behavior

  1. Set up basic astro project
  2. Install and Import Medusa like in documentation (see above)

Expected behavior

No import issue.

Code snippets

{
  "name": "project",
  "type": "module",
  "version": "0.0.1",
  "scripts": {
    "dev": "astro dev",
    "start": "astro dev",
    "build": "astro check && astro build",
    "preview": "astro preview",
    "astro": "astro"
  },
  "dependencies": {
    "@astrojs/check": "^0.9.3",
    "@astrojs/preact": "^3.5.3",
    "@astrojs/tailwind": "^5.1.1",
    "@medusajs/js-sdk": "^2.0.1",
    "@medusajs/ui": "^4.0.1",
    "astro": "^4.15.8",
    "lodash": "^4.17.21",
    "lucide-astro": "^0.447.0",
    "lucide-preact": "^0.447.0",
    "preact": "^10.24.2",
    "tailwindcss": "^3.4.12",
    "typescript": "^5.6.2"
  },
  "devDependencies": {
    "@medusajs/types": "^2.0.1",
    "@medusajs/ui-preset": "^2.0.0",
    "@tailwindcss/typography": "^0.5.15",
    "sharp": "^0.33.5"
  }
}
yannickschuchmann commented 1 month ago

For now I could add @medusajs/js-sdk to the bundle in vite/astro config:

import { defineConfig } from "astro/config";

export default defineConfig({
  vite: {
    ssr: {
      noExternal: ["@medusajs/js-sdk"],
    },
  },
});

This seems to do the trick as a workaround.