mmomtchev/pymport

Docs: All the ways to import user modules from ES6

Opened this issue · 0 comments

Note

Not tested! Please leave a comment if you have checked any of these methods.

  1. Setting PYTHONPATH in package.json using dotenv-cli:
npm i dotenv-cli

package.json:

{
    "scripts": {
        "dev": "dotenv -v PYTHONPATH=. -- node src/index.js"
    }
}

src/index.js:

const { pymport, proxify } = await import('pymport');

const my_python_module = proxify(pymport('my_python_module'));
  1. Using dynamic import:

Warning

Dynamic imports can make the code more difficult to read and manage because they add asynchronous behavior.

import path from 'node:path';
process.env['PYTHONPATH'] = path.resolve(".");

(async () => {
    const { pymport, proxify } = await import('pymport');
    const my_python_module = proxify(pymport('my_python_module'));
})();
  1. Using require in Node 23.0 (there no need for a --experimental-require-module flag):

Caution

pymport is officially tested only on Node 16.x, 18.x, and 20.x.

Note

You can read more about this in the Joyee Cheung's article and PR.

package.json:

{
  "scripts": {
    "start": "node src/index.js",
  }
}

src/index.js:

import path from 'node:path';
process.env['PYTHONPATH'] = path.resolve(".");
const { pymport, proxify } = require('pymport');

const my_python_module = proxify(pymport('my_python_module'));