Share code between widgets

When you are developing multiple widgets for one business domain, you may want to share code between them. This page describes how Experience Builder helps you to achieve this.

Experience Builder provides two methods to share code between widgets:

  • Dynamic loading: This method is straightforward to implement. However, it requires dynamic loading of the shared code, so you can't use the frequently-used ES6 import {} from ''. In addition, the shared code is compiled into the 'chunks' folder, which contains numerous files and can be challenging to maintain.
  • Shared entry: This approach allows you to import shared code using standard ES6 imports, offering a cleaner structure. However, it requires an additional setup step.

Dynamic loading

When you need to share code between widgets using this way, the best practice is to create a folder. Place the widgets that need to share code in the folder, and then create a common folder to store the shared code. The folder structure looks like this:

Use dark colors for code blocksCopy
1
2
3
4
5
widgets/
  your-folder/
    common/
    widget1/
    widget2/

In the common folder, you can export the shared code through general ES6 exports, such as export const sharedFunction = () => {}. In the widget1 and widget2 folders, you can import the shared code using dynamic loading, such as import('../../../common/my-module').then().

After compilation, the shared code is placed into the widgets/chunks folder.

See the dynamic-loading for a complete example.

Shared entry

When you need to share code between widgets using this way, please follow the steps below:

  • Create a shared-code folder under the widgets folder. Please note that the folder name must be exactly shared-code.
  • Put your shared code into the shared-code folder. All .ts and .tsx files in the folder will be compiled as shared entries. The best practice folder structure is:
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
shared-code/
  entry1.ts
  entry2.tsx
  lib/
    entry1/
      module1.ts
      module2.ts
    entry2/
      module1.ts
      module2.ts

In the above folder structure, entry1 and entry2 will be created automatically when compiling.

To support i18n, create a translations folder within the shared-code folder, or within each entry folder, for example, shared-code/translations or shared-code/lib/entry1/translations. The translations folder structure is the same as the widget translations folder.

  • At last, you can import the shared code using the standard ES6 imports, like this:
Use dark colors for code blocksCopy
1
import { sampleFunction } from 'widgets/shared-code/entry1'

After compilation, the shared entries are placed into the widgets/shared-code folder.

See the shared-entry for a complete example.

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.