We have a library implemented as a JavaScript ES6 module that we intend to use in our Yii 2 application.
Our problem arises when trying to import the module - given the asset handling, the exact location of the asset is unknown at the time of writing the code importing the module where the imported module is located at runtime, complicating the implementation.
I currently see the following three paths to importing the library:
- “Classic” static import declaration: Requires knowing the path of the module to be imported, which is however generated by the asset manager and not yet available when the importing JavaScript is written.
- Static import declaration with import maps: Allows specifying the actual URL in a separate import map. While most likely the cleanest solution, import maps only been recently (2023) been implemented in all major browsers, leading to a non-insignificant amount of users still not supporting this.
- Dynamic import: By storing the location of the library asset in a JavaScript variable, it can then be imported using a dynamic
import()
. This has only slightly lower Browser support than static import and thus appears a suitable approach. Besides stylistic disadvantages, the import will only be processed when the Browser actually executes the statement, possibly resulting in a slower execution.
Given that JavaScript modules are increasingly widespread, I am somewhat surprised that we failed to find any previous discussion on using JavaScript modules with Yii’s asset management.
Thanks!