How to import Pyodide in javascript?

69 views Asked by At

I want to run user python code on my webpage. I use Rollup to compile my module files into one bundle.js that is imported in HTML. I thought Pyodide was exactly what I needed and using it with script tags like here worked perfectly: https://pyodide.org/en/stable/usage/quickstart.html

My problem: Rollup doesn't compile when importing Pyodide in a script.

My script: editor.mjs

import {loadPyodide} from "pyodide"; // path1
// import {loadPyodide} from "node_modules/pyodide/pyodide.mjs"; // path2
// import {loadPyodide} from "./pyodide/pyodide.mjs"; // path3

async function pythonCode()
{
    const pyodide = await loadPyodide();
    return pyodide.runPython("1+1")
}

window.onload = pythonCode();

The config file: rollup.config.mjs

import {nodeResolve} from "@rollup/plugin-node-resolve";
import commonjs from '@rollup/plugin-commonjs';
import nodePolyfills from "rollup-plugin-polyfill-node";

export default {
    input: "./editor.mjs",
    output: {
        file: "./bundle.js",
        format: "iife",
        inlineDynamicImports: true,
    },
    plugins: [nodeResolve(), commonjs(), nodePolyfills()]
}

When running the command 'rollup -c' with given rollup.config file I get the following:

  • With path 1:
./editor.mjs → ./bundle.js...
(!) Circular dependencies
polyfill-node._stream_duplex.js -> polyfill-node._stream_readable.js -> polyfill-node._stream_duplex.js
polyfill-node._stream_duplex.js -> polyfill-node._stream_writable.js -> polyfill-node._stream_duplex.js
(!) Unresolved dependencies
https://rollupjs.org/troubleshooting/#warning-treating-module-as-external-dependency
node-fetch (imported by "../../../../node_modules/pyodide/pyodide.mjs")
created ./bundle.js in 799ms
  • With path 2:
./editor.mjs → ./bundle.js...
(!) Unresolved dependencies
https://rollupjs.org/troubleshooting/#warning-treating-module-as-external-dependency
node_modules/pyodide/pyodide.mjs (imported by "editor.mjs")
(!) Missing global variable name
https://rollupjs.org/configuration-options/#output-globals
Use "output.globals" to specify browser global variable names corresponding to external modules:
node_modules/pyodide/pyodide.mjs (guessing "pyodide_mjs")
created ./bundle.js in 34ms
./editor.mjs → ./bundle.js...
[!] RollupError: Could not resolve "./pyodide/pyodide.mjs" from "editor.mjs"
editor.mjs
    at Object.error (C:\Users\*****\AppData\Roaming\npm\node_modules\rollup\dist\shared\parseAst.js:279:30)
    at ModuleLoader.handleInvalidResolvedId (C:\Users\*****\AppData\Roaming\npm\node_modules\rollup\dist\shared\rollup.js:19094:36)
    at C:\Users\*****\AppData\Roaming\npm\node_modules\rollup\dist\shared\rollup.js:19054:26

Rollup does create bundles with the first 2 paths but they don't work obviously. I visited all those links and tried my best to implement the solutions they gave but I just don't understand this well enough.

What (obvious thing) am I doing wrong? Thanks

0

There are 0 answers