Re: Importing ES6 modules

"[email protected]" <[email protected]> Tue, 1 Sep 2020 07:27:32 -0700 (PDT)
Newsgroups gmane.comp.mozilla.devel.jseng
Message-ID <[email protected]>
Hi,

In general, JavaScript requires that you know certain code is a module a-priori. There are examples of code that parse as both Script and as Module yet have different results. SpiderMonkey will not try to guess. If your application wishes to take a guess, it could first try parsing as Script (since that has semantics that most people expect) and if parsing fails it could try again as Module. Your choice here would depend on what is acceptable for your application in terms of performance and predictable behaviour.

Note as well that using the `CompileModule` API you must also call  ModuleInstantiate in order to trigger loading and parsing of other modules that are imported. This all happens before executing the top-level JS code itself.

I've added an example to the embedding-examples repo. You can see the pull-request here: https://github.com/mozilla-spidermonkey/spidermonkey-embedding-examples/pull/32

--Ted

On Tuesday, September 1, 2020 at 5:30:16 AM UTC-4, Shankar wrote:
> We're trying to embed Spidermonkey76 - will look move to 78 ESR at some point - into a software that isn't a web browser. We've been looking at support for ES6 features and aren't sure about modules. 
> 
> Attempts to use local path identifiers with import commands (import MyFunc from "./whatever";) provoke an "import declarations may only appear at the top level of a module" message. 
> 
> There was a similar post a couple of years ago. One response suggested the usage of JS::CompileModule (instead of JS::Compile<Script>). How do we know that we have a module a-priori, rather than a script? 
> 
> Is the solution then to use a module resolve hook? Would it be possible to find an example? The JS API user guide doesn't include much on this topic. 
> 
> Thanks very much.