将ace代码编辑器导入webpack、es6、typescript项目

Import ace code editor into webpack, es6, typescript project

我正在尝试构建一个将托管 ace 编辑器的 Web 组件。问题是我找不到关于如何导入模块和设置类型的足够信息。使用简单的 <script> 标签和全局变量,下面的代码工作得很好。

到目前为止,这是我所拥有的:

npm install ace-code-editor --save
npm install @types/ace --save-dev

代码-editor.cmp.ts

// Error: [ts] File '.../node_modules/@types/ace/index.d.ts' is not a module.
import * as ace from 'ace';

export class CodeEditorCmp extends HTMLElement {

    // DOM
    private editor: AceAjax;  // How do I import the type. What type to use?

    constructor() {
        super();
    }

    connectedCallback() {
        this.initCodeEditor();
    }

    initCodeEditor(){

        this.editor = ace.edit("editor-vsc");

        // How do I import the editor themes?
        this.editor.setTheme("ace/theme/xcode"); 

        // How do I import the editor modes?
        var JavaScriptMode = ace.require("ace/mode/html").Mode; 

        this.editor.session.setMode(new JavaScriptMode());
        this.editor.getSession().setTabSize(4);
        this.editor.getSession().setUseSoftTabs(true);
        this.editor.getSession().setUseWrapMode(true);
        this.editor.setAutoScrollEditorIntoView(true);

        // Update document
        this.editor.getSession().on('change', this.onEditorChange);
    }

    onEditorChange(){
    }

}

require('./code-editor.cmp.scss');
window.customElements.define('editor-vsc', CodeEditorCmp);

经过大量挖掘,我设法找到了 brace 模块。它是 ace 的 browserify 包装器。幸运的是,它可以直接与 webpack 一起使用。无需使用单独的类型,它们已预先打包。

import * as ace from 'brace';
import 'brace/mode/javascript';
import 'brace/theme/monokai';

export class CodeEditorCmp extends HTMLElement {

    private editor: ace.Editor;

    initCodeEditor(){
        this.editor = ace.edit('javascript-editor');
        this.editor.getSession().setMode('ace/mode/javascript');
        this.editor.setTheme('ace/theme/monokai');
        //...
    }

    //...
}

对于那些不想使用大括号模块的人,我看到我的问题是我导入了错误版本的 ace。安装后,确保从 src-noconflict 导入。 noconflict 版本使用 ace.require,这似乎比使用 require.

的其他迭代要好得多

我建议您执行以下操作:

npm install ace-builds --save
npm install @types/ace --save-dev

然后在您的文件中导入 noconflict,如下所示:

import * as ace from 'ace-builds/src-noconflict/ace';

这将导致定义变量 ace。然后,您将能够正常引用 ace 的方法和属性,例如 ace.edit()

您可以获得有关不同版本ace的更多信息check out the git page.