javascript - Transcrypt:使用来自另一个 python 脚本的代码导致 'TypeError: module is undefined'

标签 javascript python transcrypt

我在使用 transcrypt(版本 3.6.95)跨多个文件拆分代码时遇到问题。作为一个基本示例,我在同一目录中有以下文件:

索引.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>

我的模块.py

def helloworld():
    return "Hello world!"

我的脚本.py

from mymodule import helloworld

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

然后我跑

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

它运行没有错误,并在目录 __javascript__ 中生成 mymodule.js、mymodule.mod.js、myscript.js 和 myscript.mod.js。

当我在 Firefox 58 中打开 index.htm 并打开控制台时,它显示“类型错误:模块未定义”。我试过添加 <script src="__javascript__/mymodule.js"></script>到 HTML,但这没有帮助。我通读了 this part的 transcrypt 文档,但是 -u当我键入 python -m transcrypt -h 时,switch 没有出现在可用命令列表中.

最佳答案

单元(编译单元、组件)是一个相对较新的功能,与模块相反,它从一开始就存在于 Transcrypt 中。 您需要 Transcrypt 3.6.101 才能使用单元。请注意,由于 CPython 是解释器而不是编译器,因此编译单元的概念在那里不起作用。

单元结合模块的使用展示在:

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

这个示例应该可以帮助您入门,如果没有,请在评论或编辑中告诉我。

[编辑] 所有单元(相对于模块)都应该单独编译,所以在示例中:

transcrypt -u .run animals.py

transcrypt -u .com cats.py

transcrypt -u .com dogs.py

所以模块包含带有 .run 选项的运行时和带有 .com 选项的其他组件。如果需要,可以添加 -n 开关。

在多个单元中使用的模块应该添加到运行时单元,即使用 -u .run 开关编译的单元。

关于javascript - Transcrypt:使用来自另一个 python 脚本的代码导致 'TypeError: module is undefined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48911754/

相关文章:

javascript - 如何在 Sinon.js 中测试 Controller 中使用的辅助函数

python - Azure功能不使用可用主机实例

Python 3.6 AST 模块无法识别异步方法

javascript - 快速处理程序中的 es6 和谐箭头函数

javascript - 如何杀死页面的当前进程

java - 单击 html 表行的编辑链接以填充 EditDATA_form 字段。表数据由 servlet 对 jsp 的响应填充

python - 在 Django 中获取浏览器的默认语言

python - 将多核与 LocalMRJobRunner 用于 MRJob

python - 为什么 Python 3.7 数据类不支持 < > <= 和 >=,或者它们支持?