Overview
Amplication plugins are built using Webpack, which bundles all dependencies into thedist folder. This ensures that plugins can run independently without requiring external dependencies at runtime. However, when developing multiple plugins that share common utilities or logic, duplicating code is inefficient. Instead, you can create a shared library that can be locally imported into your plugins using the method described below.
This guide explains how to create a shared library and integrate it into Amplication plugins using npm dependencies and Webpack configuration.
Creating the Shared Library
-
Create a new folder for the shared library
- Inside your plugin repository, create a new directory under root called
lib.
- Inside your plugin repository, create a new directory under root called
-
Initialize an npm package
- Navigate to
liband create a new package: - This creates a
package.jsonfile with the package nameshared.
- Navigate to
-
Add utility functions
- Inside the
shareddirectory, create anindex.tsfile and add a utility function:
- Inside the
Using the Shared Library in a Plugin
-
Add the shared library as a dependency
- Inside the
package.jsonof the target plugin, add a local dependency: - Replace
@my-orgwith your package scope if needed.
- Inside the
-
Update Webpack Configuration
- Open
webpack.config.jsin your plugin directory and add an alias for the shared package:
- Open
-
Import and Use the Shared Library
- Inside your plugin, import and use the shared utility function:
- Inside your plugin, import and use the shared utility function:
Running and Testing
- Install dependencies and build the shared package:
- Install dependencies in your plugin and run it:
- Execute the plugin to verify that the shared function is correctly used.