使用打字稿时如何添加自定义扩展

How to add a custom extension when using typescript

我正在尝试向 scrumpy/tiptap 添加自定义扩展,但我的项目使用的是打字稿,我认为这给我带来了一些问题。

我从 this issue 获得了代码,并尝试像这样导入和使用它:

import HighlightMark from '../ts/tiptap-extensions/HighlightMark';

...

this.editor = new Editor({
  content: '<p>This is just a boring paragraph.</p>',
  extensions: [new HighlightMark()]
})

但是我遇到了这个错误

Type 'HighlightMark' is not assignable to type 'ExtensionOption'. Type 'HighlightMark' is not assignable to type 'Mark'. The types returned by 'schema.toDOM(...)' are incompatible between these types. Type '(string | number | { style: string; })[]' is not assignable to type 'DOMOutputSpec'. Property '0' is missing in type '(string | number | { style: string; })[]' but required in type 'DOMOutputSpecArray'.


我尝试在 .d.ts 中导入它(因为我必须处理所有内置的 tiptap 扩展),但我收到一条错误消息,告诉我无法从相对路径导入文件这里:

Import or export declaration in an ambient module declaration cannot reference module through relative module name.ts(2439)


我也尝试过将文件更改为打字稿 (HighlightMark.ts),但它会给我几个错误:

Property 'commands' in type 'HighlightMark' is not assignable to the same property in base type 'Mark'. Type '({ type }: { type: any; }) => (attrs: any) => Command' is not assignable to type '({ type, schema, attrs }: { type: MarkType; schema: MarkSpec; attrs: { [key: string]: string; }; }) => CommandGetter'. Type '(attrs: any) => Command' is not assignable to type 'CommandGetter'.

'mark' is declared but its value is never read.ts(6133) Parameter 'mark' implicitly has an 'any' type.ts(7006)

Parameter 'attrs' implicitly has an 'any' type.ts(7006)

有没有人这样做过?真的可以吗?

这是来自 HighlightMark.js 的代码:

   import { Mark } from 'tiptap';
   import { toggleMark } from 'tiptap-commands'

  export default class HighlightMark extends Mark {
  get name() {
    return "mark";
  }

  get schema() {
    return {
      attrs: {
        color: {
          default: "rgba(240,87,100,0.7)"
        }
      },
      parseDOM: [
        {
          tag: "mark"
        }
      ],
      toDOM: mark => [
        "mark",
        {
          style: `background: red` // ${mark.attrs.color}
        },
        0
      ]
    };
  }

  commands({ type }) {
    return attrs => toggleMark(type, attrs);
  }
}

看来我可以通过像这样初始化 tiptap 来解决这个问题

this.editor = new Editor({
  content: '<p>This is just a boring paragraph.</p>',
  extensions: [new HighlightMark() as any]

这并不理想,但目前看来可行。

如果有人能post真正的解决方案我会标记为答案

我没有 运行 遇到与您相同的问题,但对我有用的方法可能会有所帮助。为了让它为我工作,我必须将 class 作为我的 .js 文件中的模块导出。对于您来说,它看起来像这样:

HighlightMark.js

import { Mark } from 'tiptap';
import { toggleMark } from 'tiptap-commands'

...

export { HighlightMark };

然后在你的主 ts 文件中


import highlightMark from '../ts/tiptap-extensions/HighlightMark';

...

this.editor = new Editor({
  content: '<p>This is just a boring paragraph.</p>',
  extensions: [ new HighlightMark() ]
})

我能够通过从 toDOM 返回对象而不是数组来解决这个问题,如下所示:

toDOM: mark => {
  return {
    0: 'mark',
    1: {
      style: `background:${mark.attrs.color}`
    },
    2: '0'
  }
}