unjs / jiti

Runtime TypeScript and ESM support for Node.js
MIT License
1.85k stars 62 forks source link

ESM: import Sentry from "@sentry/node" #211

Closed tobiasmuehl closed 1 month ago

tobiasmuehl commented 8 months ago

Environment

https://stackblitz.com/edit/stackblitz-starters-gpqjnv?file=index.ts&view=editor

Reproduction

In stackblitz terminal: npx jiti index.ts

Describe the bug

❯ npx jiti index.ts
Need to install the following packages:
jiti@1.21.0
Ok to proceed? (y) y
TypeError: Cannot read properties of undefined (reading 'init')
    at eval (file:///home/projects/stackblitz-starters-gpqjnv/index.ts:3:15)
    at evalModule (file:///home/.npm/_npx/dd8909d1e5fe7d01/node_modules/jiti/dist/jiti.js:1:256518)
    at jiti (file:///home/.npm/_npx/dd8909d1e5fe7d01/node_modules/jiti/dist/jiti.js:1:254446)
    at Object.eval (file:///home/.npm/_npx/dd8909d1e5fe7d01/node_modules/jiti/bin/jiti.js:14:1)
    at Object.function (https://stackblitzstartersgpqjnv-p5nm.w-credentialless.staticblitz.com/blitz.a9c8a5a3.js:352:194797)
    at Module._compile (https://stackblitzstartersgpqjnv-p5nm.w-credentialless.staticblitz.com/blitz.a9c8a5a3.js:54:14871)
    at Module._extensions..js (https://stackblitzstartersgpqjnv-p5nm.w-credentialless.staticblitz.com/blitz.a9c8a5a3.js:54:15550)
    at Module.load (https://stackblitzstartersgpqjnv-p5nm.w-credentialless.staticblitz.com/blitz.a9c8a5a3.js:54:13457)
    at Module._load (https://stackblitzstartersgpqjnv-p5nm.w-credentialless.staticblitz.com/blitz.a9c8a5a3.js:54:10535)
    at Function.executeUserEntryPoint [as runMain] (https://stackblitzstartersgpqjnv-p5nm.w-credentialless.staticblitz.com/blitz.a9c8a5a3.js:125:731)

Additional context

It can be fixed by fixing the imports, for example

import { init as sentryInit } from "@sentry/node"

sentryInit()

Logs

No response

peterroe commented 8 months ago

This looks to be a problem of usage with the CJS/ESM, I think there are two way to solve your problem:

  1. Use require syntax with CJS.
    const Sentry = require('@sentry/node');
  2. Use import * as syntax with ESM.
    
    import * as Sentry from '@sentry/node';
tobiasmuehl commented 8 months ago

require doesn't play nicely with VSCode/intellisense. In the stackblitz example the import * as seems to work, but it doesn't work in my actual app. I will investigate further.

pi0 commented 1 month ago

jiti v2 introduces new jiti.import() syntax that prefers native ESM imports.

If you have encountered any issues with v2 still, please ping to reopen or feel free to open new issue with reproduction 👍🏼