Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[nuxt] Error in pnpm nuxt dev mode: Cannot use import statement outside a module #13917

Closed
3 tasks done
Tracked by #9095
TrezorTop opened this issue Oct 9, 2024 · 18 comments
Closed
3 tasks done
Tracked by #9095
Assignees
Labels
Package: nuxt Issues related to the Sentry Nuxt SDK

Comments

@TrezorTop
Copy link

Is there an existing issue for this?

How do you use Sentry?

Sentry Saas (sentry.io)

Which SDK are you using?

@sentry/nuxt

SDK Version

8.33.1

Framework Version

Nuxt 3.13.0

Link to Sentry event

No response

Reproduction Example/SDK Setup

Here is my configurations:

sentry.client.config.ts

import * as Sentry from "@sentry/nuxt";

Sentry.init({
  // If set up, you can use your runtime config here
  // dsn: useRuntimeConfig().public.sentry.dsn,
  dsn: "https://417a6acdaa42cf95c2271c2fa14541d9@o4504802128101376.ingest.us.sentry.io/4508092319727616",

  // We recommend adjusting this value in production, or using tracesSampler
  // for finer control
  tracesSampleRate: 1.0,
});

sentry.server.config.ts

import * as Sentry from "@sentry/nuxt";

Sentry.init({
  dsn: "https://417a6acdaa42cf95c2271c2fa14541d9@o4504802128101376.ingest.us.sentry.io/4508092319727616",
});

Steps to Reproduce

  1. Initialize a fresh Nuxt.js project.
  2. Install the @sentry/nuxt package and add Sentry initialization (https://docs.sentry.io/platforms/javascript/guides/nuxt/).
  3. Attempt to start the project locally.

Expected Result

Nuxt app on the localhost have been successfully launched.

Actual Result

Getting 500 response from the Nuxt server instance:

[nuxt] [request error] [unhandled] [500] Cannot use import statement outside a module
  at wrapSafe (node:internal/modules/cjs/loader:1469:18)
  at Module._compile (node:internal/modules/cjs/loader:1491:20)
  at Object..js (node:internal/modules/cjs/loader:1691:10)
  at Module.load (node:internal/modules/cjs/loader:1317:32)
  at Function._load (node:internal/modules/cjs/loader:1127:12)
  at TracingChannel.traceSync (node:diagnostics_channel:315:14)
  at wrapModuleLoad (node:internal/modules/cjs/loader:217:24)
  at Module.require (node:internal/modules/cjs/loader:1339:12)
  at require (node:internal/modules/helpers:125:16)
  at C:\dev\js\nuxt-sentry-test\node_modules\.pnpm\@[email protected]_@[email protected]\node_modules\@opentelemetry\resources\build\esm\detectors\platform\node\machine-id\getMachineId.js:30:25
@getsantry getsantry bot moved this to Waiting for: Product Owner in GitHub Issues with 👀 3 Oct 9, 2024
@github-actions github-actions bot added the Package: nuxt Issues related to the Sentry Nuxt SDK label Oct 9, 2024
@s1gr1d
Copy link
Member

s1gr1d commented Oct 9, 2024

Hello, can you give us a small code reproduction so we can debug this efficiently? :)

@TrezorTop
Copy link
Author

Indeed, but my code is unremarkable. It is a brand-new, standard Nuxt project.

Here is my nuxt.config.ts:

// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
  compatibilityDate: '2024-04-03',

  devtools: { enabled: true },

  modules: ["@sentry/nuxt/module"],
})

package.json:

{
  "name": "nuxt-app",
  "private": true,
  "type": "module",
  "scripts": {
    "build": "nuxt build",
    "dev": "nuxt dev",
    "generate": "nuxt generate",
    "preview": "nuxt preview",
    "postinstall": "nuxt prepare"
  },
  "dependencies": {
    "@sentry/nuxt": "^8.33.1",
    "nuxt": "^3.13.0",
    "vue": "latest",
    "vue-router": "latest"
  },
  "packageManager": "[email protected]+sha1.9217c800d4ab947a7aee520242a7b70d64fc7638"
}

sentry.client.config.ts:

import * as Sentry from "@sentry/nuxt";

Sentry.init({
  // If set up, you can use your runtime config here
  // dsn: useRuntimeConfig().public.sentry.dsn,
  dsn: "https://417a6acdaa42cf95c2271c2fa14541d9@o4504802128101376.ingest.us.sentry.io/4508092319727616",

  // We recommend adjusting this value in production, or using tracesSampler
  // for finer control
  tracesSampleRate: 1.0,
});

sentry.server.config.ts:

import * as Sentry from "@sentry/nuxt";

Sentry.init({
  dsn: "https://417a6acdaa42cf95c2271c2fa14541d9@o4504802128101376.ingest.us.sentry.io/4508092319727616",
});

That's all. The rest is just the default Nuxt app scaffolding.

@getsantry getsantry bot moved this to Waiting for: Product Owner in GitHub Issues with 👀 3 Oct 9, 2024
@s1gr1d s1gr1d self-assigned this Oct 9, 2024
@s1gr1d
Copy link
Member

s1gr1d commented Oct 9, 2024

I'll take a look at this

@trezorsix
Copy link

trezorsix commented Oct 9, 2024

I have found that the Nuxt application builds and runs fine, but the issue only occurs when running on localhost. To resolve this, we need to enable the nuxt module only for the build process. A temporary solution would be to edit the nuxt.config.js file:

export default defineNuxtConfig({
  compatibilityDate: "2024-04-03",

  devtools: { enabled: true },

  css: ["~/assets/styles/main.css"],

  modules: [
    // "@sentry/nuxt/module" causes errors while running on localhost
    ...(process.env.ENABLE_SENTRY === 'true' ? ["@sentry/nuxt/module"] : [])
  ],

  // @ts-expect-error: @sentry/nuxt/module causes errors while running on localhost
  sentry: {
    sourceMapsUploadOptions: {
      org: "switchcase-devs",
      project: "nuxt-js-template",
      authToken: "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",
    },
  },
});

@getsantry getsantry bot moved this to Waiting for: Product Owner in GitHub Issues with 👀 3 Oct 9, 2024
@s1gr1d
Copy link
Member

s1gr1d commented Oct 10, 2024

I just checked this and with your project setup, I got the error only in development mode (with nuxt dev). But when building the project (with nuxt build) and running the build locally, it worked fine. Can you confirm?

I also tried it with npm, yarn and pnpm v8.15 (so without the package.json entry) and it worked in development mode as well. I still have to check why this causes issues with the latest pnpm version (v9).

But great that you found a workaround! In your case it makes sense to only run Sentry when you are not in dev mode. Something like this might also work:

modules: [
  ...(process.env.NODE_ENV !== 'development' ? ["@sentry/nuxt/module"] : [])
],

@trezorsix
Copy link

trezorsix commented Oct 10, 2024

Yes, the project runs properly when building with nuxt build, I can confirm that

@getsantry getsantry bot moved this to Waiting for: Product Owner in GitHub Issues with 👀 3 Oct 10, 2024
@s1gr1d s1gr1d changed the title [nuxt] Cannot use import statement outside a module [nuxt] Error in pnpm nuxt dev mode: Cannot use import statement outside a module Oct 14, 2024
@gokhantaskan
Copy link

Yes, the project runs properly when building with nuxt build, I can confirm that.

I implemented the changes successfully, but I'm encountering an issue with the Netlify build. The Nuxt config has a nitro.preset set as the netlify option. I made modifications to the start script as per the documentation.

"start": "node --env-file=.env --import ./.nuxt/dist/server/sentry.server.config.mjs .nuxt/dist/server/index.mjs"

The build has no issues, but Sentry doesn't catch any issues.

@trezorsix
Copy link

Version 8.35.0 still preserves this behaviour

@getsantry getsantry bot moved this to Waiting for: Product Owner in GitHub Issues with 👀 3 Oct 22, 2024
@s1gr1d
Copy link
Member

s1gr1d commented Oct 22, 2024

I just tried it with pnpm and couldn't reproduce the error "Cannot use import statement outside a module". But it seems like pnpm cannot resolve the dependency of import-in-the-middle and you have to explicitly add it to your dependencies. import-in-the-middle is a dependency of @sentry/node and @sentry/node is a dependency of @sentry/nuxt.

@trezorsix
Copy link

npm gives the same error with import-in-the-middle.

Attaching the Vercel logs
Image

@getsantry getsantry bot moved this to Waiting for: Product Owner in GitHub Issues with 👀 3 Oct 22, 2024
@trezorsix
Copy link

trezorsix commented Oct 22, 2024

Adding the import-in-the-middle explicitly to dependencies did not help.

@trezorsix
Copy link

I am going to use dynamicImportForServerEntry with the value of false as it helps, but I hope this is a temporary solution.

@s1gr1d
Copy link
Member

s1gr1d commented Oct 22, 2024

The error message looks similar but it's actually a slightly different one 😅
Without declaring import-in-the-middle in the pnpm dependencies, the error says "Cannot find package 'import-in-the-middle' ", as the package is not even available.

However, the error message in your screenshot says "Cannot find module ..." (it needs the hook.mjs module). Did you already add @vercel/nft as an override? You can find more information about how to set this and why this is needed in the docs here.

I understand that this can feel frustrating, and we already filed an issue upstream to Nitro to fix the missing hook.mjs file so the override is not needed anymore.

@timhn-bm
Copy link

timhn-bm commented Oct 31, 2024

Hi 👋

Same issue as @trezorsix here, using yarn berry.

  • Passing the resolutions didn't work (looking at the node_modules, we still had @vercel/nft v0.26.5 installed 🔴
  • Explicitely passing "@vercel/nft": "^0.27.4" in the devDependencies did not work either. I checked my node_modules and version 0.27.4 is indeed installed. That makes me pretty confused 🔴
  • I tried adding a plugin to copy/paste the right files but these were overriden by the nitro build process 🔴

I found a very hacky way to get it to work, but wouldn't really recommend it. Basically leveraging Nuxt's lifecycle hooks to copy-pasting the missing files to .output/server/node_modules/import-in-the-middle

  1. Added the following nitro:build:public-assets in the nuxt.config
hooks: {

  'nitro:build:public-assets': async function () {
    const { exec } = await import('child_process')
    exec('node copy-files.js', (err, stdout, stderr) => {
      if (err) {
        console.error(`exec error: ${err}`)

        return
      }
      console.log(`stdout: ${stdout}`)
      console.error(`stderr: ${stderr}`)
    })
  },
  1. Created this copy-files.js which copies the missing files to .output/server/node_modules/import-in-the-middle
// copy-files.js
import { cp, mkdir } from 'node:fs/promises'

async function main() {
  await mkdir('.output/server/node_modules/import-in-the-middle', {
    recursive: true,
  })
  
  // following calls could probably be parallelized, this is just for explanation
  await cp(
    '../../node_modules/import-in-the-middle/lib',
    '.output/server/node_modules/import-in-the-middle/lib',
    { recursive: true },
  )

  await cp(
    '../../node_modules/import-in-the-middle/hook.js',
    '.output/server/node_modules/import-in-the-middle/hook.js',
  )

  await cp(
    '../../node_modules/import-in-the-middle/hook.mjs',
    '.output/server/node_modules/import-in-the-middle/hook.mjs',
  )
}

main()

@getsantry getsantry bot moved this to Waiting for: Product Owner in GitHub Issues with 👀 3 Oct 31, 2024
@AbhiPrasad
Copy link
Member

Hey @timhn-bm! Thank you for sharing your approach + workaround.

Most of the SDK team is off on holiday tomorrow (long weekend), but we'll be back on Monday to take a look at this further. Appreciate the patience in the mean time.

@trezorsix
Copy link

@s1gr1d adding "@vercel/nft": "^0.27.4" to the package.json file helped. Thank you.

For those who it may be helpful: add this to your package.json at root level

"pnpm": {
  "overrides": {
    "@vercel/nft": "^0.27.4"
  }
},

@s1gr1d
Copy link
Member

s1gr1d commented Nov 4, 2024

Docs for this are coming soon so I will close this issue. The docs PR: getsentry/sentry-docs#11720

Ideally, Sentry users who are using pnpm don't have to explicitly add this in the future so please check the docs for updates.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Package: nuxt Issues related to the Sentry Nuxt SDK
Projects
Archived in project
Development

No branches or pull requests

6 participants