#How to import a JS file at runtime?

23 messages · Page 1 of 1 (latest)

rough hearth
#

I'm needing the ability to import a user-defined JS file at runtime (for app configuration via a JS file... a JSON file won't work).

I think the only way to do this currently via a custom Rust function (since the runtime JS doesn't have access to the file system). Is this correct?

If so, could anyone point me to some example code (https://www.secondstate.io/articles/embed-javascript-in-rust/ is the only thing that I've found which seems close but I'm new to Rust so may be missing something obvious)?

proud laurel
rough hearth
#

Thanks @proud laurel. It's helpful to know about this, but ultimately I'm not seeing where this is any different than getting a JS file as plain text via a Rust function. The issue is still that I need to somehow evaluate the text into actual JavaScript. The use of eval() seems to be be blocked by Tauri's bundler (probably for good reason) but perhaps there's some other way....

proud laurel
#

the eval() doesn't work?
what error is it

rough hearth
proud laurel
#

I think the link contains all things that you need.

rough hearth
proud laurel
#

even the content just 1?

rough hearth
#

hmm....

#

So window.eval('1') works but window.eval('var test = 1') does not work...

#

That doesn't seem right...

proud laurel
#

var test = 1 does do it things, it return undefined because you didn't return it

#

var test = 1; test

rough hearth
#

🤦‍♂️ that was the problem...

Thank you, @proud laurel !

proud laurel
#

if you need pass some value, I suggest you use the function method.

rough hearth
#

e.g.

export default { test: 123 }
#

or

return { test: 123 }
proud laurel
#

if use function, then the content could just be a regular function body

rough hearth
#

The first returns:

SyntaxError: Unexpected keyword 'export'

The second:

Return statements are only valid inside functions.

proud laurel
#
const func = new Function("arg1", "arg2", `
const sum = arg1 + arg2
return { result: arg1 + arg2 + sum }  
`)

console.log(func(1, 2)) // { result: 6 }
proud laurel