rquickjs_core/loader/
script_loader.rs1use crate::{
2 loader::{util::check_extensions, Loader},
3 Ctx, Error, Module, Result,
4};
5
6#[derive(Debug)]
10pub struct ScriptLoader {
11 extensions: Vec<String>,
12}
13
14impl ScriptLoader {
15 pub fn add_extension<X: Into<String>>(&mut self, extension: X) -> &mut Self {
17 self.extensions.push(extension.into());
18 self
19 }
20
21 #[must_use]
23 pub fn with_extension<X: Into<String>>(mut self, extension: X) -> Self {
24 self.add_extension(extension);
25 self
26 }
27}
28
29impl Default for ScriptLoader {
30 fn default() -> Self {
31 Self {
32 extensions: vec!["js".into()],
33 }
34 }
35}
36
37impl Loader for ScriptLoader {
38 fn load<'js>(&mut self, ctx: &Ctx<'js>, path: &str) -> Result<Module<'js>> {
39 if !check_extensions(path, &self.extensions) {
40 return Err(Error::new_loading(path));
41 }
42
43 let source: Vec<_> = std::fs::read(path)?;
44 Module::declare(ctx.clone(), path, source)
45 }
46}