Attribute Macro rquickjs::module

source ·
#[module]
Available on crate feature macro only.
Expand description

An attribute which generates code for exporting a module to Rust.

Any supported item inside the module which is marked as pub will be exported as a JavaScript value. Different items result in different JavaScript values. The supported items are:

  • struct and enum items. These will be exported as JavaScript classes with their constructor exported as a function from the module.
  • fn items, these will be exported as JavaScript functions.
  • use items, the types which are reexported with pub will be handled just like struct and enum items defined inside the module. The name of the class can be adjusted by renaming the reexport with as.
  • const and static items, these items will be exported as values with the same name.

§Attribute options

The attribute has a number of options for configuring the generated trait implementation. These attributes can be passed to the module attribute as an argument: #[module(rename = "AnotherName")] or with a separate qjs attribute on the impl item: #[qjs(rename = "AnotherName")]. A option which is a Flag can be set just by adding the attribute: #[qjs(flag)] or by setting it to specific boolean value: #[qjs(flag = true)].

OptionValueDescription
crateStringChanges the name from which the attribute tries to use rquickjs types. Use when the name behind which the rquickjs crate is declared is not properly resolved by the macro.
renameStringChanges the name of the implemented module on the JavaScript side.
rename_varsCasingAlters the name of all items exported as JavaScript values by changing the case. Can be one of lowercase, UPPERCASE, camelCase, PascalCase,snake_case, or SCREAMING_SNAKE
rename_typesCasingAlters the name of all items exported as JavaScript classes by changing the case. Can be one of lowercase, UPPERCASE, camelCase, PascalCase,snake_case, or SCREAMING_SNAKE
prefixStringThe module will be implemented for a new type with roughly the same name as the Rust module with a prefix added. This changes the prefix which will be added. Defaults to js_

§Item options

The attribute also has a number of options for changing the resulting generated module implementation for specific items. These attributes are all in the form of #[qjs(option = value)].

OptionValueItem TypeDescription
skipFlagAllSkips exporting this item from the JavaScript module.
renameStringAll except useChange the name from which this value is exported.
declareFlagFunctions OnlyMarks this function as the declaration function. This function will be called when the module is declared allowing for exporting items which otherwise are difficult to export using the attribute.
evaluateFlagFunctions OnlyMarks this function as the evaluation function. This function will be called when the module is being evaluated allowing for exporting items which otherwise are difficult to export using the attribute.

§Example


use rquickjs::{CatchResultExt, Context, Module, Runtime};

/// A class which will be exported from the module.
#[derive(rquickjs::class::Trace)]
#[rquickjs::class]
pub struct Test {
    foo: u32,
}

#[rquickjs::methods]
impl Test {
    #[qjs(constructor)]
    pub fn new() -> Test {
        Test { foo: 3 }
    }
}

impl Default for Test {
    fn default() -> Self {
        Self::new()
    }
}

#[rquickjs::module(rename_vars = "camelCase")]
mod test_mod {
    /// Imports and other declarations which aren't `pub` won't be exported.
    use rquickjs::Ctx;

    /// You can even use `use` to export types from outside.
    ///
    /// Note that this tries to export the type, not the value,
    /// So this won't work for functions.
    ///
    /// By using `as` you can change under which name the constructor is exported.
    /// The below type will exported as `RenamedTest`.
    pub use super::Test as RenamedTest;

    /// A class which will be exported from the module under the name `FooBar`.
    #[derive(rquickjs::class::Trace)]
    #[rquickjs::class(rename = "FooBar")]
    pub struct Test2 {
        bar: u32,
    }

    /// Implement methods for the class like normal.
    #[rquickjs::methods]
    impl Test2 {
        /// A constructor is required for exporting types.
        #[qjs(constructor)]
        pub fn new() -> Test2 {
            Test2 { bar: 3 }
        }
    }

    impl Default for Test2 {
        fn default() -> Self {
            Self::new()
        }
    }

    /// Two variables exported as `aConstValue` and `aStaticValue` because of the `rename_all` attr.
    pub const A_CONST_VALUE: f32 = 2.0;
    pub static A_STATIC_VALUE: f32 = 2.0;

    /// If your module doesn't quite fit with how this macro exports you can manually export from
    /// the declare and evaluate functions.
    #[qjs(declare)]
    pub fn declare(declare: &mut rquickjs::module::Declarations) -> rquickjs::Result<()> {
        declare.declare("aManuallyExportedValue")?;
        Ok(())
    }

    #[qjs(evaluate)]
    pub fn evaluate<'js>(
        _ctx: &Ctx<'js>,
        exports: &mut rquickjs::module::Exports<'js>,
    ) -> rquickjs::Result<()> {
        exports.export("aManuallyExportedValue", "Some Value")?;
        Ok(())
    }

    /// You can also export functions.
    #[rquickjs::function]
    pub fn foo() -> u32 {
        1 + 1
    }

    /// You can make items public but not export them to JavaScript by adding the skip attribute.
    #[qjs(skip)]
    pub fn ignore_function() -> u32 {
        2 + 2
    }
}


fn main() {
    assert_eq!(test_mod::ignore_function(), 4);
    let rt = Runtime::new().unwrap();
    let ctx = Context::full(&rt).unwrap();

    ctx.with(|ctx| {
        // These modules are declared like normal with the declare_def function.
        // The name of the module is js_ + the name of the module. This prefix can be changed
        // by writing for example `#[rquickjs::module(prefix = "prefix_")]`.
        Module::declare_def::<js_test_mod, _>(ctx.clone(), "test").unwrap();
        let _ = Module::evaluate(
            ctx.clone(),
            "test2",
            r"
            import { RenamedTest, foo,aManuallyExportedValue, aConstValue, aStaticValue, FooBar } from 'test';
            if (foo() !== 2){
                throw new Error(1);
            }
            "
        )
        .catch(&ctx)
        .unwrap();
    })
}