Dominic Price
Dominic Price

Reputation: 1146

Transcrypt: using code from another python script causes 'TypeError: module is undefined'

I am having trouble splitting code across multiple files using transcrypt (version 3.6.95). As a basic example, I have the following files in the same directory:

index.htm

<html>
  <head>
    <meta charset="utf-8">
    <title>Transcrypt test</title>
</head>
<body>
  <div id="box"></div>
  <button onclick="myscript.set_box_content()">Set box content</button>
</body>
<script src="__javascript__/myscript.js"></script>    
</html>

mymodule.py

def helloworld():
    return "Hello world!"

myscript.py

from mymodule import helloworld

def set_box_content():
    document.getElementById("box").innerHTML = helloworld()

I then run

python -m transcrypt -n mymodule.py
python -m transcrypt -n myscript.py

Which runs without error and generates mymodule.js, mymodule.mod.js, myscript.js and myscript.mod.js in the directory __javascript__.

When I open index.htm in Firefox 58 and open the console it says 'TypeError: module is undefined'. I have tried adding <script src="__javascript__/mymodule.js"></script> to the HTML but this does not help. I read through this part of the transcrypt documentation, but the -u switch does not appear in the list of available commands when I type python -m transcrypt -h.

Upvotes: 3

Views: 360

Answers (1)

Jacques de Hooge
Jacques de Hooge

Reputation: 7000

Units (compilation units, components) are a relatively new feature, as opposed to modules, that have been in Transcrypt from the start. You need Transcrypt 3.6.101 to use units. Note that since CPython is an interpreter rather than a compiler, the concept of a compilation unit plays no role there.

The use of units in combination with modules is shown in:

https://transcrypt.org/docs/html/special_facilities.html#transcrypt-s-unit-mechanism-and-creating-native-javascript-component-frameworks

This example should get you started, if not please let me know in a comment or edit.

[EDIT] All units (as opposed to modules) should be compiled separately, so in the example:

transcrypt -u .run animals.py

transcrypt -u .com cats.py

transcrypt -u .com dogs.py

So the module containing the runtime with the .run option and the other components with the .com option. The -n switch can be added if desired.

Modules that are used in multiple units should be added to the runtime unit, that is the one compiled with the -u .run switch.

Upvotes: 2

Related Questions