stuck
stuck

Reputation: 1570

HTML with Transcrypt script gives missing { before try block error

I am trying to add a javascript file that generated via Transcrypt from Python file.

However, when I add that script to my HTML file, there are some errors appeared in Console and I failed.

The Python file that I used: try.py

def greet():
    name = document.getElementById("Name").value
    if name == "" or name.length == 0 or name == null:
        document.getElementById("groet").innerHTML = '<p><font color="#ff0000">Hello Anonymous, may I know yor name? Please insert it below:</font></p>'
    else:
        document.getElementById("groet").innerHTML = '<p><font color="#00ff00">Hello, '+name+', thank you for introducing you</font></p>'

After that script, I ran the command python3 -m transcrypt -b try.py and a folder called "target" created automatically and it contains a file "try.js".

So, I wrote a HTML file which is a basic sample that shows a greeting message: hello.html

<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="__target__/try.js"></script>
</head>
<title>Insert Text</title>
<body onload=try.greet()>

<h2>Hello Demo Name</h2>

<p>
<div id = "groet">...</div>
</p>
<p>Your Name: <input name="name" type="text" maxlength="80" id="Name" value=""/> [Please enter your name]<br><br>
<button onclick=try.greet()>Refresh the greeting!</button>
</p>
</body>
</html>

I am expecting that when I clicked the button or reload the file the greeting message should be placed. However, in console I got two errors:

Uncaught SyntaxError: import declarations may only appear at top level of a module try.js:1:13
Uncaught SyntaxError: missing { before try block hello.html:1:3

So, what is the problem guys?

[EDIT] After the T.J's answer, I updated the html file as following:

'use strict';import{AssertionError,AttributeError,BaseException,DeprecationWarning,Exception,IndexError,IterableError,KeyError,NotImplementedError,RuntimeWarning,StopIteration,UserWarning,ValueError,Warning,__JsIterator__,__PyIterator__,__Terminal__,__add__,__and__,__call__,__class__,__envir__,__eq__,__floordiv__,__ge__,__get__,__getcm__,__getitem__,__getslice__,__getsm__,__gt__,__i__,__iadd__,__iand__,__idiv__,__ijsmod__,__ilshift__,__imatmul__,__imod__,__imul__,__in__,__init__,__ior__,__ipow__,
__irshift__,__isub__,__ixor__,__jsUsePyNext__,__jsmod__,__k__,__kwargtrans__,__le__,__lshift__,__lt__,__matmul__,__mergefields__,__mergekwargtrans__,__mod__,__mul__,__ne__,__neg__,__nest__,__or__,__pow__,__pragma__,__proxy__,__pyUseJsNext__,__rshift__,__setitem__,__setproperty__,__setslice__,__sort__,__specialattrib__,__sub__,__super__,__t__,__terminal__,__truediv__,__withblock__,__xor__,abs,all,any,assert,bool,bytearray,bytes,callable,chr,copy,deepcopy,delattr,dict,dir,divmod,enumerate,filter,float,
getattr,hasattr,input,int,isinstance,issubclass,len,list,map,max,min,object,ord,pow,print,property,py_TypeError,py_iter,py_metatype,py_next,py_reversed,py_typeof,range,repr,round,set,setattr,sorted,str,sum,tuple,zip}from"./org.transcrypt.__runtime__.js";var __name__="__main__";export var greet=function(){var py_name=document.getElementById("Name").value;if(py_name==""||py_name.length==0||py_name==null)document.getElementById("groet").innerHTML='<p><font color="#ff0000">Hello Anonymous, may I know yor name? Please insert it below:</font></p>';
else document.getElementById("groet").innerHTML='<p><font color="#00ff00">Hello, '+py_name+", thank you for introducing you</font></p>"};

//# sourceMappingURL=hello.map
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script type="module">
      import { greet } from "./hello.js";
      document.getElementById("greetButton").onclick=greet();
    </script>
  </head>
  <title>Insert Text</title>
<body>

<h2>Hello Demo Name</h2>

<p>
<div id = "groet">...</div>
</p>
<p>Your Name: <input name="name" type="text" maxlength="80" id="Name" value=""/> [Please enter your name]<br><br>
<button id="greetButton">Refresh the greeting!</button>
</p>

</body>
</html>

Upvotes: 0

Views: 209

Answers (2)

stuck
stuck

Reputation: 1570

In addition to @T.J. Crowder's answer, I changed the script in html as:

<script type="module">
  import * as hello from "./__target__/hello.js";
  window.hello = hello;
</script>

As explained in the tutorial of Transcrypt.

With this way, I can call the Python function on button's click.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075209

import declarations may only appear at top level of a module

is fairly clear: You're not loading the script as a module, so you can't use import. Add type="module" to the script tag. (But be sure that your target browsers support modules -- all modern major ones do, but you don't have to go more than a few versions back in some before module support isn't there.)

missing { before try block

You have

<body onload=try.greet()>

try is a keyword in JavaScript, you can't use it as an identifier. You'll need to use a different name for your try object. (I'll use xtry in the rest of this answer.)

If your code really is a module, you also won't be able to use your xtry as a global, even if it's declared at the top level of your code, because the top level scope of a module isn't global scope. You'll need to import it to use it. That also means you don't need a script tag for try.js since the import will do it. Remove the onload and your current script tag and instead:

<script type="module">
import { xtry } from "__target__/try.js";
xtry.greet();
</script>

That won't run until the HTML has been fully parsed and the DOM has been populated (because of the type="module").


Side note: onload attribute handlers are generally not best practice, for two reasons: 1. They can only use globals, and 2. The load event happens very late in the page load cycle, waiting for all resources (including all images) to load. Sometimes that's what you want, but not often. Instead, use modern event handling (if you really need to hook up a handler on load) and use modern script techniques (type="module", defer, ...).

Upvotes: 1

Related Questions