TranscryptOrg / Transcrypt

Python 3.9 to JavaScript compiler - Lean, fast, open!
https://www.transcrypt.org
Apache License 2.0
2.86k stars 215 forks source link

Multiline literal JS that is ignored by CPython #871

Closed JGreenlee closed 7 months ago

JGreenlee commented 7 months ago

I want to include a few lines of raw JavaScript code that will be taken as-is during compilation, but will be ignored by CPython.

The way I've found to include literal JS is with # __pragma__ ('js', '{}', '<JavaScript code>'). But this only works for single-line statements because "comment-like" variety pragmas only work with # (single-line comments).

I wish I could do something like this:

""" __pragma__('js', '{}', '''
  function foo() {
    console.log("bar");
  }
''')
"""

Is there any workaround?

JennaSys commented 7 months ago

I've done something like this before where I create a Python reference to it (typically because I want to call the function elsewhere in the Python code). Transcrypt will then create an export for the function in the generated JS file:

foo = __pragma__('js', '''
  function foo() {{
    console.log("bar");
  }}
''')

The generated JS code then looks like this:

export var foo=function foo(){console.log("bar")};
JGreenlee commented 7 months ago

I've done something like this before where I create a Python reference to it (typically because I want to call the function elsewhere in the Python code). Transcrypt will then create an export for the function in the generated JS file:

Although that's not specifically what I was looking for, your reply made me realize I can do what I want to do by using pragmas inside executable comments:

'''?
__pragma__('js', '{}', """
  function foo() {
    console.log("bar");
  }
""")
?'''

As long as the ecom pragma is active; or the --ecom command line switch


This is helpful for my use case, where I am basically exposing a library as both a Python package and a JS package. I have started detailing a summary of tips relevant to that use case here: https://github.com/JGreenlee/e-mission-common?tab=readme-ov-file#tips-for-writing-code-to-work-in-both-python-and-javascript

JGreenlee commented 7 months ago

But the short answer is yes, you can do it with:

'''?
__pragma__('js', '{}', """
  function foo() {
    console.log("bar");
  }
""")
?'''

The only weird thing is that there's extra indentation in the output JS file. But since JS is not sensitive to indentation level, I don't care and this works fine.