首页 > 解决方案 > 如何在 stenciljs 中添加 npm ckeditor4?

问题描述

我已经将 npm i ckeditor4 安装到我的模板项目中,并且我已经像这样使用它。但我没有得到ckeditor,告诉我在哪里添加脚本标签我对模具完全陌生

ui-editor.tsx

import { Component, h } from '@stencil/core';

@Component({
    tag: 'ui-editor',
    styleUrl: 'style.scss',
    shadow: true
})

export class UiEditor {
    render() {
        return (
            <div id="editor">
                <p>This is the editor content.</p>
            </div>
        )
    }
}

正如文档https://www.npmjs.com/package/ckeditor4中所说,我应该在哪里添加脚本

<script src="./node_modules/ckeditor4/ckeditor.js"></script>
<script>
    CKEDITOR.replace( 'editor' );
</script>

标签: ckeditor4.xstenciljs

解决方案


尝试从 index.html 文件中删除脚本标记。以下组件将自动从 unpkg 添加脚本标签。

webcomponents.dev 上的示例

import { h, Component, State, Host } from "@stencil/core";

@Component({
  tag: "ck-editor"
})
export class CkEditor {
  _textarea: HTMLTextAreaElement;

  componentWillLoad() {
    return this.appendScript();
  }

  componentDidLoad() {
    //@ts-ignore
    let editor = CKEDITOR.replace(this._textarea, {
      width: "99%",
      height: "300px",
    });
  }

  private async submit() {
    // @ts-ignore
    console.log(
      CKEDITOR.instances[
        this._textarea.nextSibling.id.replace("cke_", "")
      ].getData()
    );
  }

  appendScript() {
    return new Promise((resolve) => {
      if (document.getElementById("ckeditor-script")) {
        resolve();
        return;
      }
      const ckeditorScript = document.createElement("script");
      ckeditorScript.id = "ckeditor-script";
      ckeditorScript.src = "https://unpkg.com/ckeditor4@4.14.1/ckeditor.js";
      ckeditorScript.onload = () => resolve();
      document.body.appendChild(ckeditorScript);
    });
  }

  render() {
    return (
      <Host>
        <textarea ref={(el) => (this._textarea = el)}></textarea>
        <button onClick={() => this.submit()}>Submit</button>
      </Host>
    );
  }
}

您应该能够导入 ckeditor 但我还没有测试过它在汇总中的处理方式。我最近从事的项目已经从 unpkg 加载 ckeditor,所以我们改为朝那个方向发展。


推荐阅读