jerryscript-project / jerryscript

Ultra-lightweight JavaScript engine for the Internet of Things.
https://jerryscript.net
Apache License 2.0
6.89k stars 669 forks source link

Import and Export statement #5018

Closed DiamondToken closed 2 years ago

DiamondToken commented 2 years ago

how to use import statement without syntax error in v2.4.0?

zherczeg commented 2 years ago

Did you pass -m to jerryscript? From api, you need to pass a flag to jerry_parse.

DiamondToken commented 2 years ago

i made it import and export, but with different parse options i can get either import, export or scope. if i parse with JERRY_PARSE_MODULE i can import but my scope is empty if i parse with JERRY_PARSE_NO_OPTS i can see some variables in the scope via globalThis

in both cases i can't see variables and functions from c code like this

`
interpret = jerryx_get_property_str(global_obj_val, "interpret");

jerry_release_value(global_obj_val);

if (jerry_value_is_function(interpret)) 

`

zherczeg commented 2 years ago

Imported variables goes to a local scope, they are not part of the global object. The jerry_module_namespace can be used to get the export namespace. If you also export the imported symbols, they are available there. A module can also export a helper function with eval to get the local variables (or do anything else): export function access(s) { return eval(s) }

dananderson commented 2 years ago

Imports are different from normal requires. The process is as follows:

jerry_parse() with JERRY_PARSE_MODULE option returns a module object. The module object is in the unlinked state. Next, you need to call jerry_module_link() on the module. That moves it to the linked state (and resolves any imports of that module). Finally, call jerry_module_evaluate() to run the module.

If you want the exports, such as your interpret method, use jerry_module_namespace() to get the exports from C.

The jerry implementation follows the ECMA spec with respect to modules. But, making a usable import system takes some work.

DiamondToken commented 2 years ago

in v2.4.0 there is no such thing like jerry_module_link. I want to get function which lives in JS from C.

dananderson commented 2 years ago

Oh, I did not realize 2.4.0 was so outdated. I don't see a public api in 2.4.0 for accessing an es module's exports.

DiamondToken commented 2 years ago

anyway, many thanks to you! @dananderson @zherczeg