microsoft / ClearScript

A library for adding scripting to .NET applications. Supports V8 (Windows, Linux, macOS) and JScript/VBScript (Windows).
https://microsoft.github.io/ClearScript/
MIT License
1.77k stars 148 forks source link

ScriptEngineException: SyntaxError: Cannot use import statement outside a module #491

Closed jnilsson89 closed 1 year ago

jnilsson89 commented 1 year ago

I am working on a Worker Service project that includes the ClearScript NuGet package. ClearScript enables me to call JavaScript functions from my C# code without importing modules, which has been working great so far. However, I need to import a file in my JavaScript code using the "node-fetch" library in my .js file.

The line of code I have added is: import fetch from 'node-fetch'.

Unfortunately, when I run ExecuteDocument, the application crashes with the following error message: "ScriptEngineException: SyntaxError: Cannot use import statement outside a module."

Although I have read that using a JavaScript engine should be possible, I am still very new to this technology and have been unable to find a solution to get my code running. Thank you in advance for any assistance you can provide.

ClearScriptLib commented 1 year ago

Hi @jnilsson89,

Unfortunately, when I run ExecuteDocument, the application crashes with the following error message: "ScriptEngineException: SyntaxError: Cannot use import statement outside a module."

The import declaration is valid only within a module. If you're using ClearScript's V8ScriptEngine, you can execute a document as a JavaScript module as follows:

// using Microsoft.ClearScript.JavaScript;
engine.ExecuteDocument(pathOrUrl, ModuleCategory.Standard);

Keep in mind however that node-fetch, like most npm packages, is likely to be dependent on the Node.js API, whereas ClearScript provides only the standard JavaScript built-ins, aiming to make it easy to use .NET to provide additional facilities.

Good luck!