Skip to content

Instantly share code, notes, and snippets.

@oakfang
Last active April 7, 2023 04:45
Show Gist options
  • Save oakfang/f65e10dd10992045c968 to your computer and use it in GitHub Desktop.
Save oakfang/f65e10dd10992045c968 to your computer and use it in GitHub Desktop.
How to import js modules into python
import sys
import jiphy # pip install
from os import path
from types import ModuleType
class JsFinder(object):
def find_module(self, name, m_path):
name += '.js'
if m_path is not None:
name = path.join(m_path[0], name)
if path.exists(name):
return JsLoader(name)
class JsLoader(object):
def __init__(self, name):
self.name = name
with open(name) as content:
self.content = content.read()
def load_module(self, name):
module = ModuleType(name)
exec(jiphy.to.python(self.content), module.__dict__)
return module
sys.meta_path.append(JsFinder())
import js
import pure
print pure.add(5, 7)
function add(a, b) {
return a + b;
}
@kirankotari
Copy link

does this work? you are adding JsFinder object to the path.

@kiritom107
Copy link

it say me : "Import "index" could not be resolvedPylancereportMissingImports" what should i do?

@oakfang
Copy link
Author

oakfang commented Jun 13, 2021

the module jiphy doesn't support requiring external modules: https://github.com/timothycrosley/jiphy#syntax--contstructs-jiphy-suppports

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment