【问题标题】:ReferenceError: Require not defined when trying to use jquery in angular2ReferenceError:尝试在angular2中使用jquery时要求未定义
【发布时间】:2016-05-02 09:44:25
【问题描述】:

我无法将 jQuery 与 angular2 一起使用。我的一个朋友让它工作的地方(在 Mac 上)它不在我的 Windows 机器上。

错误:

jquery-ui.js:1 Uncaught ReferenceError: require is not defined
angular2.dev.js:23935 EXCEPTION: TypeError: jQuery(...).find(...).sortable is not a function in [null]
angular2.dev.js:23925 EXCEPTION: TypeError: jQuery(...).find(...).sortable is not a function in [null]BrowserDomAdapter.logError @ angular2.dev.js:23925
angular2.dev.js:23925 ORIGINAL EXCEPTION: TypeError: jQuery(...).find(...).sortable is not a functionBrowserDomAdapter.logError @ angular2.dev.js:23925
angular2.dev.js:23925 ORIGINAL STACKTRACE:BrowserDomAdapter.logError @ angular2.dev.js:23925
angular2.dev.js:23925 TypeError: jQuery(...).find(...).sortable is not a function at EditPresentationComponent.ngOnInit 

我们使用 jquery 的那段代码。

import { Component, OnInit, ElementRef, Inject } from 'angular2/core';

declare var jQuery: any;

    @Component({
        selector: 'edit-presentation',
        templateUrl: 'app/Edit Presentation/edit_presentation.component.html'
    })

export class EditPresentationComponent implements OnInit {
    elementRef: ElementRef;

    isMyPresentationEmpty = true;

    constructor(@Inject(ElementRef) elementRef: ElementRef) {
        this.elementRef = elementRef;
    }

    ngOnInit() {
        var self = this;

        // Initialize Sortable on lists
        var oldList, newList, item, oldIndex;
        jQuery(this.elementRef.nativeElement).find('.slide-categories .sortable-list').sortable({
            start: function(event, ui) {
                item = ui.item;
                oldIndex = item.index();
                newList = oldList = ui.item.parent().parent();
            },
            change: function(event, ui) {  
                if (ui.sender) newList = ui.placeholder.parent().parent();
                // Check for empty list and hide/show instruction text
                if (jQuery('.my-presentation-column .agile-list').has('li:not(".ui-sortable-helper")').length) {
                    self.isMyPresentationEmpty = false;
                } else {
                    self.isMyPresentationEmpty = true;
                }
            },
            stop: function(event, ui) {
                if (oldList[0] != jQuery(event.toElement).parent().parent().parent().parent()[0]) {
                    if (jQuery(event.target).parent().hasClass('slide-categories')) {
                        if (oldIndex == 0) {
                            jQuery(event.target).prepend(item.clone());
                        } else {
                            jQuery(event.target).find('li:eq(' + (oldIndex - 1) + ')').after(item.clone());
                        }
                    } else {
                        item.remove();
                    }
                }
            },
            connectWith: ".sortable-list"
        }).disableSelection();

当我执行 npm install jquery 或 npm install jquery-ui 时,我得到了

`--jquery-ui@1.10.5 extraneous

结果,所以它被安装了。

我希望有人可以帮助我。

【问题讨论】:

  • 如果您删除declare var jQuery: any; 是否有效?
  • 那么它无法编译,因为它找不到任何函数或名称
  • typescript 编译器可能会出错,但函数会运行。
  • [0] app/Edit Presentation/edit_presentation.component.ts(32,21): error TS2304: C annot find name 'jQuery'.

标签: jquery typescript angular referenceerror


【解决方案1】:

如果你使用 typescript 和 angular2,你应该只安装 jquery 和 jquery-ui 的类型。然后你可以像这样加载 jQuery:

import "jquery-ui"
import * as $ from "jquery"

您似乎遇到的另一个问题是 jquery-ui 正在寻找 require,这在浏览器中是不存在的。我会仔细检查您是如何加载 jquery-ui 的,因为它也可能会引入错误

【讨论】:

  • 我无法在没有错误的情况下包含此内容。错误在 jquery-ui 文件中
【解决方案2】:

这是我的工作方式:

  • 在主 HTML 文件中包含相应的 JS 文件

    <script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
    <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
    
  • jquery().storable 包装到自定义指令中

    @Directive({
      selector: '[sortable]'
    })
    export class SortableDirective {
      constructor(private elementRef:ElementRef) {
      }
    
      ngOnInit() {
        $(this.elementRef.nativeElement).sortable({
          start: function(event, ui) {
            console.log('start');
          },
          change: function(event, ui) {  
            console.log('change');
          },
          stop: function(event, ui) {
            console.log('stop');
          }
        }).disableSelection();
      }
    }
    
  • 这样使用

    @Component({
      selector: 'app',
      template: `
        <ul sortable>
          <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 1</li>
          <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 2</li>
        </ul>
    `,
      directives: [ SortableDirective ]
    })
    export class App implements AfterViewInit {
    }
    

看到这个 plunkr:https://plnkr.co/edit/gQnKzqdHCY82LOCFM1ym?p=preview

关于 require 问题,你可以从 SystemJS 加载 jquery-ui,因为它理解 require 函数。这是一个示例:

<script>
  System.config({
    map: {
      'jquery-ui': 'nodes_module/.../jquery-ui.js'
    }
  });
</script>

那么你可以这样导入:

import jqueryui from 'jquery-ui';

【讨论】:

    猜你喜欢
    • 2016-04-22
    • 1970-01-01
    • 2017-02-04
    • 2015-06-12
    • 2021-11-08
    • 2018-03-01
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    相关资源
    最近更新 更多