Closed DraftedDev closed 1 year ago
Hi!
I noticed a bunch of problems in your code.
First, in order to load the module console
it also needs to be resolved.
So you need to call add_module
on the builtin resolver with console
.
Second, you declare the resolver but you don't use it in Runtime::set_loader
.
Third, console is a module so it isn't defined on the global object but must be imported, like so:
import * as console from "console";
console.log();
In order to import modules the javascript must also be a module, so instead of calling Ctx::eval
and the like, use Module::evaluate
.
Here is the code I ended up with experimenting with yours, this seems to work with the above javascript.
use rquickjs::context::EvalOptions;
use rquickjs::loader::{
BuiltinLoader, BuiltinResolver, FileResolver, ModuleLoader, NativeLoader, ScriptLoader,
};
use rquickjs::module::ModuleDef;
use rquickjs::prelude::Func;
use rquickjs::{CatchResultExt, Context, Module, Runtime, Value};
use std::path::{Path, PathBuf};
mod console;
#[derive(Debug)]
pub struct AeRuntime {
//config: AeConfig, // just a { strict, global, std } struct, ignore
loader: ModuleLoader,
resolver: BuiltinResolver,
paths: Vec<String>,
}
impl AeRuntime {
pub fn new() -> Self {
Self {
loader: ModuleLoader::default(),
resolver: BuiltinResolver::default(),
paths: vec![],
}
}
pub fn add_std(&mut self) {
self.loader.add_module("console", console::Console); // add to loader
// Add console to be resolved.
self.resolver.add_module("console");
}
pub fn run(mut self, script: &Path) {
let runtime = Runtime::new().unwrap();
self.add_std();
runtime.set_loader(
// set loader + resolver
(
FileResolver::default().with_native().with_paths(self.paths),
// Add resolver as part of the loader.
self.resolver,
),
(
BuiltinLoader::default(),
NativeLoader::default(),
ScriptLoader::default(),
self.loader,
),
);
let context = Context::full(&runtime).expect("Failed to create context");
let script = std::fs::read_to_string(script).unwrap();
context.with(|ctx| {
let globals = ctx.globals();
// Evaluate the javascript as a module..
Module::evaluate(ctx, "main", script)
.map(|_| ())
.catch(ctx)
.unwrap();
});
}
}
WOW! That helped 👍 Thanks for your help and sorry for the stupid issue.
Hi, I'm sorry for bothering you again, but I got an issue while trying to "register" a native module. I want to add the native module impl (not the macro one) to the module loader and the resolver, however with the code I've written, quickjs throws "Module "console" not found".
This is my code:
My JS code:
My example.rs code:
My console module:
Thanks for your help :D