Using a Shared Library in Amplication Plugins
Learn how to create and use a shared library across multiple Amplication plugins using npm and Webpack configuration.
Overview
Amplication plugins are built using Webpack, which bundles all dependencies into the dist
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
lib
and create a new package: - This creates a
package.json
file with the package nameshared
.
- Navigate to
-
Add utility functions
- Inside the
shared
directory, create anindex.ts
file and add a utility function:
- Inside the
Using the Shared Library in a Plugin
-
Add the shared library as a dependency
- Inside the
package.json
of the target plugin, add a local dependency: - Replace
@my-org
with your package scope if needed.
- Inside the
-
Update Webpack Configuration
- Open
webpack.config.js
in 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.
Conclusion
Using a shared library in Amplication plugins allows you to centralize reusable utilities, improving maintainability and consistency across multiple plugins. By setting up local dependencies and Webpack aliases, you can seamlessly integrate shared functions into your development workflow.
Was this page helpful?