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