This example demonstrates how to use Rspack for generating code at build time and executing it at runtime.
In this example, we use Rspack to generate a JavaScript file at build time that contains a dynamic function. This function is then executed at runtime.
-
CodeGenPlugin.js:
- This is a custom Rspack plugin responsible for generating JavaScript code at build time.
- The plugin creates a
generated.jsfile inside thedistfolder. - The generated code exports a simple function
dynamicGreetingwhich logs a greeting message.
-
Rspack Configuration:
- The plugin is added to the
rspack.config.jsfile under thepluginssection. - The configuration ensures that the plugin runs at the appropriate phase during the Rspack build process.
- The plugin is added to the
-
Generated Code (
generated.js):- This file contains the generated
dynamicGreetingfunction, which will be executed at runtime. - The code is simple: it logs a greeting message with a dynamic input.
- This file contains the generated
-
Runtime Execution (
index.js):- The main code in
index.jsimports thedynamicGreetingfunction fromgenerated.jsand executes it. - The
generated.jsfile is dynamically injected by the plugin at build time. - The
dynamicGreetingfunction is called during runtime to display a greeting message.
- The main code in
- Rspack compiles the project using the custom plugin.
- At build time, the plugin generates
generated.jsin thedistfolder. - When running the application,
index.jsimports the generated file and executes the function, which prints a dynamic greeting message to the console.
- CodeGenPlugin: Generates the
generated.jsfile. - Rspack Configuration: Ensures the plugin is executed during the build process.
- Generated Code: Contains the
dynamicGreetingfunction, which is imported and executed at runtime.
This setup allows code generation at build time, with the generated code being injected into the project and executed during runtime.
- Clone the repository.
- Run
yarn buildto generate the code. - Run
yarn startto execute the application and see the greeting message in the console.