Extending Univer in JavaScript
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 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 decorator is the parameter decorators provided by @univerjs/core
. Here we will introduce how to replace this decorator 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