Univer
Univer Slide
Advanced Usage
Extending Univer in JavaScript

Extending Univer in JavaScript

📊📝📽️ Univer General
💡

If you find that the decorators are not working properly in some projects that integrate TypeScript support (usually because the implementation of the babel-related decorator plugin is inconsistent with TypeScript), you can also consider using this method to replace the decorators.

To facilitate development, Univer uses a large number of TypeScript decorators (opens in a new tab) to declare dependency injection relationships.

Therefore, we certainly recommend that you use TypeScript first. However, if you are not familiar with TypeScript or are constrained by other reasons, you can also use JavaScript to extend Univer. Of course, this is not an easy task, as you may need to understand the internal mechanism of Univer and how to use JavaScript to implement decorators in TypeScript.

In Univer's documentation, the most common decorators are the parameter decorators provided by @univerjs/core and the OnLifecycle class decorators. Here we will introduce how to replace these two decorators in JavaScript.

Parameter Decorators

@univerjs/core provides the setDependencies method to explicitly declare dependencies in JavaScript. For example:

- import { Plugin, ICommandService, UniverInstanceType } from '@univerjs/core'
+ import { Plugin, ICommandService, UniverInstanceType, Injector, setDependencies } from '@univerjs/core'
 
export class MyPlugin extends Plugin {
  static override type = UniverInstanceType.UNIVER_UNKNOWN
  static override pluginName = 'MY_PLUGIN_NAME'
 
-  constructor(@Inject(Injector) protected readonly _injector: Injector, @ICommandService private readonly _commandService: ICommandService) {
+  constructor(_injector, _commandService) {
    super()
 
+   this._injector = _injector
+   this._commandService = _commandService
  }
 
-  override onStarting(injector: Injector): void {
+  override onStarting(injector) {
-    ([[ConfigService]] as Dependency[]).forEach(d => injector.add(d))
+    [[ConfigService]].forEach(d => injector.add(d))
  }
}
 
+ setDependencies(MyPlugin, [Injector, ICommandService])

Reference: https://redi.wendell.fun/docs/javascript (opens in a new tab)

Class Decorator OnLifecycle

The OnLifecycle class decorator is used to declare lifecycles. @univerjs/core provides the runOnLifecycle method to explicitly declare lifecycles in JavaScript. For example:

- import { Disposable, LifecycleStages, OnLifecycle } from '@univerjs/core'
+ import { Disposable, LifecycleStages, runOnLifecycle } from '@univerjs/core'
 
- @OnLifecycle(LifecycleStages.Steady, MYController)
export class MYController extends Disposable {
}
 
+ runOnLifecycle(LifecycleStages.Steady, MYController)

Copyright © 2021-2024 DreamNum Co,Ltd. All Rights Reserved.