Angular 2 включает пакет ng2-ace


Я пытался заставить работать пакет npm ng2-ace для используя тег ace-editor в div, но я всегда получаю сообщение об ошибке «Не удается найти модуль ng2-ace».


Итак, это мой app.component.ts.

import { Component } from '@angular/core';

import { AceEditorDirective } from 'ng2-ace';

@Component({
  selector: 'my-app',
  directives: [AceEditorDirective],
  templateUrl: 'app/app.component.html'
})

export class AppComponent { }


А это мой app.component.ts

/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/',
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',
      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      // other libraries
      'rxjs':                      'npm:rxjs',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',

      'brace': 'npm:brace',
      'w3c-blob': 'npm:w3c-blob',
      'buffer': 'npm:buffer-shims',
      'ng2-ace': 'npm:ng2-ace'
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      },
      'angular-in-memory-web-api': {
        main: './index.js',
        defaultExtension: 'js'
      },

      'ng2-ace': {
        format: 'cjs',
        defaultExtension: 'js',
        main: './index.js'
      },

      'w3c-blob': {
        format: 'cjs',
        defaultExtension: 'js',
        main: './index.js'
      },

      'brace': {
        format: 'cjs',
        defaultExtension: 'js',
        main: './index.js'
      },

      'buffer': {
        format: 'cjs',
        defaultExtension: 'js',
        main: './index.js'
      },
    }
  });
})(this);

скобка является зависимостью ng2-ace, которая имеет зависимость w3c-blob, которая также имеет буфер depencey.
Я только начал работать с Angular 2, поэтому не очень привык к рабочему процессу.

В любом случае Заранее спасибо!


person Thomas Fellner    schedule 08.10.2016    source источник
comment
Какую версию Angular2 вы используете?   -  person Sefa    schedule 08.10.2016
comment
2.0.2 Я предполагаю или что именно вы имеете в виду?   -  person Thomas Fellner    schedule 08.10.2016
comment
Можете ли вы проверить, какая у вас версия пакетов @angular/* в вашем файле package.json?   -  person Sefa    schedule 08.10.2016
comment
@Sefa Да, у меня на всех 2.0.2, хотя @angular/router 3.0.2   -  person Thomas Fellner    schedule 08.10.2016


Ответы (2)


Вы можете попробовать выполнить следующие шаги для настройки ace-editor.

шаг 1

Установить пакеты

npm i brace w3c-blob buffer base64-js ieee754 --save

шаг 2

Создать директиву:

import { Directive, ElementRef, EventEmitter, Input, Output } from '@angular/core';

import 'brace';
import 'brace/theme/monokai';
import 'brace/mode/javascript';
declare var ace: any;

@Directive({
  selector: '[ace-editor]'
})
export class AceEditorDirective {
  _readOnly: any;
  _theme: any;
  _mode: any;

  editor: any;
  oldVal: any;

  @Input() set options(value) {
    this.editor.setOptions(value || {});
  }

  @Input() set readOnly(value) {
    this._readOnly = value;
    this.editor.setReadOnly(value);
  }

  @Input() set theme(value) {
    this._theme = value;
    this.editor.setTheme(`ace/theme/${value}`);
  }

  @Input() set mode(value) {
    this._mode = value;
    this.editor.getSession().setMode(`ace/mode/${value}`);
  }

  @Input() set text(value) {
    if(value === this.oldVal) return;
    this.editor.setValue(value);
    this.editor.clearSelection();
    this.editor.focus();
  }

  @Output() textChanged = new EventEmitter();
  @Output() editorRef = new EventEmitter();

  constructor(private elementRef: ElementRef) {
    const el = elementRef.nativeElement;
    el.classList.add('editor');

    this.editor = ace.edit(el);

    setTimeout(() => {
      this.editorRef.next(this.editor);
    });

    this.editor.on('change', () => {
      const newVal = this.editor.getValue();
      if(newVal === this.oldVal) return;
      if(typeof this.oldVal !== 'undefined') {
        this.textChanged.next(newVal);
      }
      this.oldVal = newVal;
    });
  }
}

шаг 3

Настройте systemjs.config.js

  map: {
    ...

    'brace': 'npm:[email protected]',
    'w3c-blob': 'npm:w3c-blob/index.js',
    'buffer': 'npm:buffer/index.js',
    'base64-js': 'npm:base64-js/index.js',
    'ieee754': 'npm:ieee754/index.js'   
  },
  packages: {
    ...
    brace: {
      main: './index.js',
      defaultExtension: 'js'
    }
  }

шаг 4

Включите AceEditorDirective в declarations список вашего модуля.

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent, AceEditorDirective ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Наслаждайтесь

person yurzui    schedule 08.10.2016
comment
Я заставил его работать другим, более хакерским способом, но гораздо более чистым, поэтому я буду его использовать. Спасибо! - person Thomas Fellner; 08.10.2016
comment
Опубликуйте также свою конфигурацию systemjs. пробовал на локальной машине - person yurzui; 08.10.2016
comment
Хорошо, извините, я забыл одну строку, теперь это работает. Спасибо за помощь! - person Thomas Fellner; 08.10.2016

Потому что ng2-ace пропустил определения Typescript. Итак, компилятор Angular выдает ошибку: 'Cannot find module ng2-ace'. Я думаю, вы можете создать пользовательскую директиву из ng2-ace для использования в своем проекте.

Надеюсь, это поможет!

person Ha Hoang    schedule 08.10.2016
comment
но ng2-ace использует Typescript. В библиотеке есть одно определение директивы. Моя проблема в том, что я не могу получить к нему доступ. Я предполагаю, что что-то не так в systemjs.config.js - person Thomas Fellner; 08.10.2016
comment
Выдает ошибку при запуске приложения в браузере? - person Ha Hoang; 08.10.2016
comment
@Ha_Hoang Я не могу запустить его в браузере из-за ошибки - person Thomas Fellner; 08.10.2016
comment
Я запускаю его из консоли. Но вывод: pastebin.com/znGMdtTv - person Thomas Fellner; 08.10.2016
comment
Как я уже упоминал, поскольку ng2-ace не имеет определения машинописного текста, это вызывает ошибку: app/app.module.ts(13,36): ошибка TS2307: не удается найти модуль «ng2-ace». Взгляните на github.com/seiyria/ng2-ace/issues/1 - person Ha Hoang; 08.10.2016