svaarala / duktape

Duktape - embeddable Javascript engine with a focus on portability and compact footprint
MIT License
5.97k stars 515 forks source link

import keyword? #2414

Open Honya2000 opened 3 years ago

Honya2000 commented 3 years ago

I have lot of JS files with such construction:

import CreateTempUserReq from 'xyz/model/CreateTempUserReq.js';

Duktape throws syntax errors on those lines.

Is this means i cannot use duktape to execute my JS files ?

Honya2000 commented 3 years ago

I tried to use such construction instead of import:

var mod = require('foo/bar');

Initialized duktape module by calling duk_module_duktape_init.

But duktape doesn't recognize require and reports: [JavaScript] Evaluate: TypeError: undefined not callable

svaarala commented 3 years ago

ES2015 import is not supported at present.

For duk_module_duktape_init() to work you need to supply a function to resolve modules based on their name. In concrete terms, when given a module name (say foo/bar) it must return the module source code. Here are more details and examples: https://wiki.duktape.org/howtomodules.

Honya2000 commented 3 years ago

Ok, I can live without import and export somehow (though have to modify over 100 files...).

But there is another more important thing: I'm evaluating 2 scripts on the same duktape context:

  1. first script has function post declared: function post(path, textArea, responseDisplay, req, clbk) { var url = 'http://localhost:8183/' + path; ... }

  2. Second script has construction: post("user", null, null, req, function(resp) { //console.log("Resp: " + JSON.stringify(resp)); ... }); Duktape throws error on second script: Evaluate: ReferenceError: identifier 'post' undefined

Is this also not supported ?

svaarala commented 3 years ago

How are you evaluating the script - in an "eval" context or a "program" context? This, and also whether the script is strict or not, affects how new bindings (especially globals) are created.

Here's a pure JS example of eval() and strictness:

> eval('function foo() {}')
undefined
> typeof foo
'function'
> eval('"use strict"; function bar() {}')
'use strict'
> typeof bar
'undefined'

So in an eval() context a global is established for a non-strict script but not for a strict script.

If you want to evaluate scripts as programs (similar to how browser scripts are evaluated), you can use duk_pcompile_string() and duk_pcall(). With no flags given to duk_pcompile_string(), the script compiles as a "program" by default.