denoland / deno

A modern runtime for JavaScript and TypeScript.
https://deno.com
MIT License
94.63k stars 5.25k forks source link

NPM error: 'import', and 'export' cannot be used outside of module code at ... #17784

Open aW4KeNiNG opened 1 year ago

aW4KeNiNG commented 1 year ago

Hi.

I'm trying to use the Kobalte lib on a Deno project but I'm getting the next error:

error: 'import', and 'export' cannot be used outside of module code at file:///C:/Users/aw4ke/AppData/Local/deno/npm/registry.npmjs.org/@kobalte/core/0.6.0/dist/esm/index.js:1:1

  import { access, accessWith, getDocument, EventKey, getActiveElement, contains, ...

You can replicate the issue with the next code:

import { Button } from 'npm:@kobalte/core';

console.log(typeof Button);

and deno run -A .\test.ts

There is a similar opened issue (#17231) using another lib , but I have tried esm.sh, skypack.dev, etc... and it doesn't work either.

Any help is appreciated.

aapoalas commented 1 year ago

The library has a fairly complicated exports / entry point definition:

  "exports": {
    ".": {
      "solid": "./dist/source/index.jsx",
      "import": "./dist/cjs/index.js",
      "browser": {
        "import": "./dist/esm/index.js",
        "require": "./dist/cjs/index.js"
      },
      "require": "./dist/cjs/index.js",
      "node": "./dist/cjs/index.js"
    }
  },
  "main": "dist/cjs/index.js",
  "module": "dist/esm/index.js",
  "types": "dist/types/index.d.ts",

I tested and verified that Deno is taking the exports["."].import path here, but indeed apparently somehow still thinks that it's importing CJS. If I manually changed the import entry to use the cjs path then the module is loaded (though throws from another issue, apparently).

axetroy commented 1 year ago

same with me, and here is a more simple entry point definition.

  "main": "dist/cjs/index.js",
  "exports": {
    ".": {
      "require": "./dist/cjs/index.js",
      "import": "./dist/esm/index.js"
    }
  },
import { FileSystemWalker } from "npm:file-system-walker@1.0.12";
GJZwiers commented 1 year ago

I did some debugging, the problem appears to be that while the right ESM entry point is used, the closest package.json does not have a type field specified, causing Deno to apply CommonJS module resolution https://github.com/denoland/deno/blob/da5b5d4688f03e578565966b1c0634a187f7729d/cli/node/mod.rs#L473-L482