extremeheat / JSPyBridge

🌉. Bridge to interoperate Node.js and Python
MIT License
701 stars 55 forks source link

error when using with python in a directory that is declared to be a js-module #149

Open spike-rabbit opened 1 week ago

spike-rabbit commented 1 week ago

Reproduction Repo: https://github.com/spike-rabbit/python-js-module-bug The important part is, that the venv are in the same directory or below the projects package.json.

Error:

[JSE] ReferenceError: require is not defined in ES module scope, you can use import instead

[JSE] This file is being treated as an ES module because it has a '.js' file extension and '/home/***/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

[JSE]     at file:///home/***/.venv/lib/python3.13/site-packages/javascript/js/bridge.js:9:14

[JSE]     at ModuleJob.run (node:internal/modules/esm/module_job:218:25)

[JSE]     at async ModuleLoader.import (node:internal/modules/esm/loader:329:24)

[JSE]     at async loadESM (node:internal/process/esm_loader:28:7)

[JSE]     at async handleMainPromise (node:internal/modules/run_main:113:12)

Potential solutions

Sure, I could move things around in my project to get rid of the module problem.

But the much nicer solutions would be either:

extremeheat commented 10 hours ago

Can you please elaborate more on how you got this error (and your proposed fix?)

spike-rabbit commented 7 hours ago

Thx for replying and taking care.

Sorry for the initial incomplete description. I now added a reproduction repo and slightly improved solution suggestions. I can create a PR once you decided for a preferred solution approach.

extremeheat commented 5 hours ago

Can't reproduce on a new github codespace:

➜ /workspaces/python-js-module-bug (main) $ poetry install
Creating virtualenv python-js-module-WaJCDlOP-py3.12 in /home/codespace/.cache/pypoetry/virtualenvs
Installing dependencies from lock file

Package operations: 1 install, 0 updates, 0 removals

  - Installing javascript (1!1.2.1)
➜ /workspaces/python-js-module-bug (main) $ poetry run python python-that-imports-js.py
[
  '.git',
  '.gitignore',
  'README.md',
  'module-based-js-file.js',
  'package-lock.json',
  'package.json',
  'poetry.lock',
  'pyproject.toml',
  'python-that-imports-js.py'
]
➜ /workspaces/python-js-module-bug (main) $ node --version
v20.17.0
➜ /workspaces/python-js-module-bug (main) $ python --version
Python 3.12.1
spike-rabbit commented 5 hours ago

This works as your .venv is not in /workspaces/python-js-module-bug.

So the projects package.json is not interfering with the .venv js files.